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 }

Updated on: 27-Mar-2020

419 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements