MongoDB query to implement aggregate function

MongoDBDatabaseBig Data Analytics

Let us first create a collection with documents −

> db.demo121.insertOne(
...    {
...       "Id" : 101,
...       "Details" : [
...          {
...             "SubjectId" : "1",
...             "SubjectName" : "MongoDB",
...             "Score" : 76
...          },
...          {
...             "SubjectId" : "2",
...             "SubjectName" : "MySQL",
...             "Score" : 76
...          },
...          {
...             "SubjectId" : "3",
...             "SubjectName" : "Java",
...             "Score" : 76
...          }
...       ]
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e2f1c60140daf4c2a3544b3")
}

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

> db.demo121.find();

This will produce the following output −

{
   "_id" : ObjectId("5e2f1c60140daf4c2a3544b3"), "Id" : 101, "Details" : [
      { "SubjectId" : "1", "SubjectName" : "MongoDB", "Score" : 76 },
      { "SubjectId" : "2", "SubjectName" : "MySQL", "Score" : 76 },
      { "SubjectId" : "3", "SubjectName" : "Java", "Score" : 76 }
   ]
}

Following is the query to implement aggregate function −

> db.demo121.aggregate([
...    { "$match": { "Id": 101 } },
...    { "$unwind": "$Details" },
...    {
...       "$group": {
...          "_id": "$Details.SubjectId",
...          "count": { "$sum": 1 },
...          "Details": {
...             "$push": {
...                "SubjectName": "$Details.SubjectName"
...             }
...          }
...       }
...    },
...    {
...       "$group": {
...          "_id": null,
...          "List": {
...             "$push": {
...                "SubId": "$_id",
...                "Details": "$Details"
...             }
...          }
...       }
...    }
... ], function (err, out) {
...    res.json(out);
... });

This will produce the following output −

{
   "_id" : null, "List" : [
      { "SubId" : "3", "Details" : [ { "SubjectName" : "Java" } ] },
      { "SubId" : "2", "Details" : [ { "SubjectName" : "MySQL" } ] },
      { "SubId" : "1", "Details" : [ { "SubjectName" : "MongoDB" } ] }
   ] 
}
raja
Published on 31-Mar-2020 15:00:01
Advertisements