- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHPPhysics
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
Using aggregation pipeline to fetch records in MongoDB
The MongoDB aggregation pipeline has stages. Each stage transforms the documents as they pass through the pipeline.
Let us first create a collection with documents −
> db.demo218.insertOne({"Name":"Chris","Branch":"CS",Marks:[65,78,36,90]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e3e5f4903d395bdc2134712")
}
> db.demo218.insertOne({"Name":"David","Branch":"ME",Marks:[56,45,42,51]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e3e5f6203d395bdc2134713")
}
> db.demo218.insertOne({"Name":"Chris","Branch":"CS",Marks:[78,65,89]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e3e5f6c03d395bdc2134714")
}
Display all documents from a collection with the help of find() method −
> db.demo218.find();
This will produce the following output −
{ "_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 ] }
Following is the query for aggregation pipeline −
> db.demo218.aggregate([
... { "$unwind": "$Marks" },
... { "$match":
... {
... "Branch": "CS",
... "Marks": { "$gt": 88 }
... }
... },
... { "$group":
... {
... "_id": "$_id",
... "Branch": { "$first": "$Branch" },
... "Marks": { "$first": "$Marks" }
... }
... }
...])
This will produce the following output −
{ "_id" : ObjectId("5e3e5f6c03d395bdc2134714"), "Branch" : "CS", "Marks" : 89 }
{ "_id" : ObjectId("5e3e5f4903d395bdc2134712"), "Branch" : "CS", "Marks" : 90 }Advertisements