Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Get substring in MongoDB aggregate
To extract substring in MongoDB aggregation pipelines, use the $substr operator within the $project stage. This operator extracts a portion of a string starting from a specified position and length.
Syntax
db.collection.aggregate([
{
$project: {
fieldName: { $substr: ["$sourceField", startIndex, length] }
}
}
])
Sample Data
db.demo176.insertMany([
{"ProductName": "PRODUCT-1"},
{"ProductName": "PRODUCT-102"},
{"ProductName": "PRODUCT-105"}
])
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e3843a09e4f06af551997ef"),
ObjectId("5e3843a69e4f06af551997f0"),
ObjectId("5e3843aa9e4f06af551997f1")
]
}
Example: Extract First 7 Characters
Extract the first 7 characters from ProductName field ?
db.demo176.aggregate([
{
$project: {
ProductName: { $substr: ["$ProductName", 0, 7] }
}
}
])
{"_id": ObjectId("5e3843a09e4f06af551997ef"), "ProductName": "PRODUCT"}
{"_id": ObjectId("5e3843a69e4f06af551997f0"), "ProductName": "PRODUCT"}
{"_id": ObjectId("5e3843aa9e4f06af551997f1"), "ProductName": "PRODUCT"}
Key Points
-
$substrparameters: [sourceField, startIndex, length] - Index starts from 0 (zero-based indexing)
- Use within
$projectstage to create new fields or modify existing ones
Conclusion
The $substr operator provides efficient string extraction in MongoDB aggregation pipelines. Specify the source field, starting position, and desired length to extract precise substrings from text data.
Advertisements
