How to aggregate array documents in MongoDB?


For this, use the aggregate framework. Let us first create a collection with documents −

> db.aggregateArrayDemo.insertOne(
   {
      "_id":100,
      "UserDetails": [
         {
            "UserName": "John",
            "UserLoginYear":2010
         },
         {
            "UserName": "Carol",
            "UserLoginYear":2019
         }
      ]
   }
);
{ "acknowledged" : true, "insertedId" : 100 }

Following is the query to display all documents from a collection with the help of find() method −

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

This will produce the following output −

{
   "_id" : 100,
   "UserDetails" : [
      {
         "UserName" : "John",
         "UserLoginYear" : 2010
      },
      {
         "UserName" : "Carol",
         "UserLoginYear" : 2019
      }
   ]
}

Following is the query to aggregate array documents −

> db.aggregateArrayDemo.aggregate([
   {
      $match: { _id: 100 }
   },
   {
      $project: {
         Minimum: { $min: "$UserDetails.UserLoginYear" },
         Maximum: { $max: "$UserDetails.UserLoginYear" }
      }
   }
]);

This will produce the following output −

{ "_id" : 100, "Minimum" : 2010, "Maximum" : 2019 }

Updated on: 30-Jul-2019

144 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements