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
Aggregation: group date in nested documents (nested object) and display the count?
To group dates in nested documents and display their count in MongoDB, use the aggregation pipeline with $unwind to flatten the array, then $group to count occurrences of each date.
Syntax
db.collection.aggregate([
{ $unwind: "$arrayField" },
{
$group: {
_id: "$arrayField.dateField",
count: { $sum: 1 }
}
}
]);
Sample Data
db.demo717.insertOne({
"shippingdetails": [
{ "duedate": "2020-04-29 22:33:04" },
{ "duedate": "2020-03-29 22:33:04" },
{ "duedate": "2020-04-29 22:33:04" },
{ "duedate": "2020-01-29 22:33:04" }
]
});
{
"acknowledged": true,
"insertedId": ObjectId("5ea9b3cd85324c2c98cc4c30")
}
Verify Sample Data
db.demo717.find().pretty();
{
"_id": ObjectId("5ea9b3cd85324c2c98cc4c30"),
"shippingdetails": [
{ "duedate": "2020-04-29 22:33:04" },
{ "duedate": "2020-03-29 22:33:04" },
{ "duedate": "2020-04-29 22:33:04" },
{ "duedate": "2020-01-29 22:33:04" }
]
}
Group Dates and Count Occurrences
db.demo717.aggregate([
{ $unwind: "$shippingdetails" },
{
$group: {
_id: "$shippingdetails.duedate",
count: { $sum: 1 }
}
}
]);
{ "_id": "2020-01-29 22:33:04", "count": 1 }
{ "_id": "2020-03-29 22:33:04", "count": 1 }
{ "_id": "2020-04-29 22:33:04", "count": 2 }
How It Works
-
$unwindcreates separate documents for each array element -
$groupgroups by the date field and counts occurrences using$sum: 1 - The
_idfield becomes the grouping key (date value)
Conclusion
Use $unwind followed by $group to count duplicate dates in nested arrays. This approach efficiently aggregates data from nested documents and provides occurrence counts for each unique date value.
Advertisements
