MongoDB aggregation with equality inside array?



For this, use aggregate() along with $group. Let us create a collection with documents −

> db.demo578.insertOne(
...    {
...       "_id" : 1,
...       "Info" : {
...          "firstName" : "Chris",
...          "lastName" : "Brown"
...       },
...
...       "achievements" : [
...          {
...             "winner" : "10th",
...             "year" : 2010,
...             "by" : "School"
...          },
...          {
...             "winner" : "12th",
...             "year" : 2012,
...             "by" : "School"
...          },
...          {
...             "winner" : "Good Rank",
...             "year" : 2012,
...             "by" : "College"
...          }
...       ]
...    }
... );
{ "acknowledged" : true, "insertedId" : 1 }

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

> db.demo578.find();

This will produce the following output −

{ "_id" : 1, "Info" : { "firstName" : "Chris", "lastName" : "Brown" }, "achievements" : [
   { "winner" : "10th", "year" : 2010, "by" : "School" },
   { "winner" : "12th", "year" : 2012, "by" : "School" },
   { "winner" : "Good Rank", "year" : 2012, "by" : "College" }
] }

Following is the query for aggregation with equality inside an array −

> db.demo578.aggregate([
...    {
...       "$unwind": "$achievements"
...    },
...    {
...       "$group": {
...          "_id": {
...             "year": "$achievements.year",
...             "firstName": "$Info.firstName",
...             "lastName": "$Info.lastName"
...          },
...          "count": { "$sum": 1 },
...          "AchievementName": { "$push": "$Info" }
...       }
...    },
...    {
...       "$match": { "count": 2 }
...    },
...    {
...       "$project": {
...          "_id": 0,
...          "year": "$_id.year",
...          "AchievementName": 1,
...          "count": 1
...       }
...    }
... ]).pretty();

This will produce the following output −

{
   "count" : 2,
   "AchievementName" : [
      {
         "firstName" : "Chris",
         "lastName" : "Brown"
      },
      {
         "firstName" : "Chris",
         "lastName" : "Brown"
      }
   ],
   "year" : 2012
}
raja
Published on 15-May-2020 09:28:29
Advertisements