Get substring in MongoDB aggregate


To get substring, use $substr in MongoDB. Let us create a collection with documents −

> db.demo176.insertOne({"ProductName":"PRODUCT-1"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3843a09e4f06af551997ef")
}
> db.demo176.insertOne({"ProductName":"PRODUCT-102"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3843a69e4f06af551997f0")
}
> db.demo176.insertOne({"ProductName":"PRODUCT-105"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3843aa9e4f06af551997f1")
}

Display all documents from a collection with the help of find() method −

> db.demo176.find();

This will produce the following output −

{ "_id" : ObjectId("5e3843a09e4f06af551997ef"), "ProductName" : "PRODUCT-1" }
{ "_id" : ObjectId("5e3843a69e4f06af551997f0"), "ProductName" : "PRODUCT-102" }
{ "_id" : ObjectId("5e3843aa9e4f06af551997f1"), "ProductName" : "PRODUCT-105" }

Following is the query to get substring in MongoDB aggregate −

> db.demo176.aggregate(
...   [
...      {
...         $project:
...            {
...
...               ProductName: { $substr: [ "$ProductName", 0, 7] }
...
...            }
...      }
...   ]
...)

This will produce the following output −

{ "_id" : ObjectId("5e3843a09e4f06af551997ef"), "ProductName" : "PRODUCT" }
{ "_id" : ObjectId("5e3843a69e4f06af551997f0"), "ProductName" : "PRODUCT" }
{ "_id" : ObjectId("5e3843aa9e4f06af551997f1"), "ProductName" : "PRODUCT" }

Updated on: 27-Mar-2020

457 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements