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

  • $unwind creates separate documents for each array element
  • $group groups by the date field and counts occurrences using $sum: 1
  • The _id field 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.

Updated on: 2026-03-15T03:42:14+05:30

312 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements