Tutorialspoint

1 Answer
Anvi Jain

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 }

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.