- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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" }
Advertisements