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
Using aggregation pipeline to fetch records in MongoDB
The MongoDB aggregation pipeline processes documents through multiple stages, where each stage transforms the documents as they pass through the pipeline. It's a powerful framework for data analysis and transformation operations.
Syntax
db.collection.aggregate([
{ $stage1: { /* stage operations */ } },
{ $stage2: { /* stage operations */ } },
{ $stageN: { /* stage operations */ } }
])
Sample Data
db.demo218.insertMany([
{"Name": "Chris", "Branch": "CS", "Marks": [65, 78, 36, 90]},
{"Name": "David", "Branch": "ME", "Marks": [56, 45, 42, 51]},
{"Name": "Chris", "Branch": "CS", "Marks": [78, 65, 89]}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e3e5f4903d395bdc2134712"),
ObjectId("5e3e5f6203d395bdc2134713"),
ObjectId("5e3e5f6c03d395bdc2134714")
]
}
Display all documents from the collection ?
db.demo218.find();
{ "_id": ObjectId("5e3e5f4903d395bdc2134712"), "Name": "Chris", "Branch": "CS", "Marks": [65, 78, 36, 90] }
{ "_id": ObjectId("5e3e5f6203d395bdc2134713"), "Name": "David", "Branch": "ME", "Marks": [56, 45, 42, 51] }
{ "_id": ObjectId("5e3e5f6c03d395bdc2134714"), "Name": "Chris", "Branch": "CS", "Marks": [78, 65, 89] }
Example: Find CS Students with Marks > 88
Use aggregation pipeline to fetch CS branch students having marks greater than 88 ?
db.demo218.aggregate([
{ "$unwind": "$Marks" },
{ "$match": {
"Branch": "CS",
"Marks": { "$gt": 88 }
}},
{ "$group": {
"_id": "$_id",
"Name": { "$first": "$Name" },
"Branch": { "$first": "$Branch" },
"Marks": { "$first": "$Marks" }
}}
]);
{ "_id": ObjectId("5e3e5f6c03d395bdc2134714"), "Name": "Chris", "Branch": "CS", "Marks": 89 }
{ "_id": ObjectId("5e3e5f4903d395bdc2134712"), "Name": "Chris", "Branch": "CS", "Marks": 90 }
How It Works
- $unwind: Deconstructs the Marks array, creating separate documents for each mark
- $match: Filters documents where Branch is "CS" and Marks > 88
- $group: Groups results back by document _id, keeping the first matching mark
Conclusion
MongoDB aggregation pipeline enables complex data processing through sequential stages. Use $unwind, $match, and $group stages to transform array data and apply filtering conditions effectively.
Advertisements
