
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
MongoDB Aggregation with Multiple Keys
To implement aggregation with multiple keys, use aggregate() along with $group. Let us create a collection with documents −
> db.demo190.insertOne( ... { ... ... "DueDate" : ISODate("2020-01-01"), ... "Value" : 10, ... "Name" : "Chris" ... } ...); { "acknowledged" : true, "insertedId" : ObjectId("5e3ad76403d395bdc21346bf") } > > db.demo190.insertOne( ... { ... ... "DueDate" : ISODate("2020-02-05"), ... "Value" : 30, ... "Name" : "David" ... } ...); { "acknowledged" : true, "insertedId" : ObjectId("5e3ad76403d395bdc21346c0") } > db.demo190.insertOne( ... { ... ... "DueDate" : ISODate("2020-01-01"), ... "Value" : 40, ... "Name" : "Chris" ... } ...); { "acknowledged" : true, "insertedId" : ObjectId("5e3ad7f003d395bdc21346c1") }
Display all documents from a collection with the help of find() method −
> db.demo190.find();
This will produce the following output −
{ "_id" : ObjectId("5e3ad76403d395bdc21346bf"), "DueDate" : ISODate("2020-01-01T00:00:00Z"), "Value" : 10, "Name" : "Chris" } { "_id" : ObjectId("5e3ad76403d395bdc21346c0"), "DueDate" : ISODate("2020-02-05T00:00:00Z"), "Value" : 30, "Name" : "David" } { "_id" : ObjectId("5e3ad7f003d395bdc21346c1"), "DueDate" : ISODate("2020-01-01T00:00:00Z"), "Value" : 40, "Name" : "Chris" }
Following is the query to implement MongoDB aggregation with multiple keys −
> db.demo190.aggregate( [ { "$group": { "_id": { "Name": "$Name", "DueDate": { "$year": "$DueDate" } }, "Value": { "$sum": "$Value" } } } ], function(err,results) { console.log(results); } );
This will produce the following output −
{ "_id" : { "Name" : "David", "DueDate" : 2020 }, "Value" : 30 } { "_id" : { "Name" : "Chris", "DueDate" : 2020 }, "Value" : 50 }
Advertisements