Aggregation: group date in nested documents (nested object) and display the count?


For aggregation, use aggregate() in MongoDB. Group the dates with $group. Let us create a collection with documents −

> 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")
}

Display all documents from a collection with the help of find() method −

> db.demo717.find().pretty();

This will produce the following output −

{
   "_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"
      }
   ]
}

Following is the query for aggregation to group date in nested documents (nested object) −

> db.demo717.aggregate(
...    {
...       $unwind:"$shippingdetails"},
...       {
...          $group: {
...             _id: "$shippingdetails.duedate",
...          count: {
...             $sum: 1
...          }
...       }
...    }
... )

This will produce the following output −

{ "_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 }

Updated on: 14-May-2020

200 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements