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
MongoDB aggregation with multiple keys
MongoDB aggregation with multiple keys allows you to group documents by several fields simultaneously. Use the $group stage with a composite _id object containing multiple grouping fields.
Syntax
db.collection.aggregate([
{
$group: {
_id: {
field1: "$field1",
field2: "$field2"
},
aggregatedField: { $operator: "$fieldToAggregate" }
}
}
]);
Sample Data
db.demo190.insertMany([
{
"DueDate": ISODate("2020-01-01"),
"Value": 10,
"Name": "Chris"
},
{
"DueDate": ISODate("2020-02-05"),
"Value": 30,
"Name": "David"
},
{
"DueDate": ISODate("2020-01-01"),
"Value": 40,
"Name": "Chris"
}
]);
Display all documents from the collection ?
db.demo190.find();
{ "_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" }
Example: Group by Name and Year
Group documents by Name and extract the year from DueDate, then sum the Values ?
db.demo190.aggregate([
{
$group: {
_id: {
Name: "$Name",
DueDate: { $year: "$DueDate" }
},
Value: { $sum: "$Value" }
}
}
]);
{ "_id": { "Name": "David", "DueDate": 2020 }, "Value": 30 }
{ "_id": { "Name": "Chris", "DueDate": 2020 }, "Value": 50 }
How It Works
- The
_idfield contains an object with multiple grouping keys -
$yearextracts the year portion from the DueDate field -
$sumaggregates the Value field for each group combination - Documents with the same Name and year are grouped together
Conclusion
Use composite _id objects in $group to aggregate by multiple fields. This enables complex grouping scenarios where documents must match on several criteria simultaneously.
Advertisements
