MongoDB GroupBy to set status


For this, you can use aggregate() in MongoDB. Let us create a collection with documents −

> db.demo149.insertOne({"Status":40});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e350386fdf09dd6d08539c4")
}
> db.demo149.insertOne({"Status":40});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e350388fdf09dd6d08539c5")
}
> db.demo149.insertOne({"Status":50});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e35038afdf09dd6d08539c6")
}

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

> db.demo149.find();

This will produce the following output −

{ "_id" : ObjectId("5e350386fdf09dd6d08539c4"), "Status" : 40 }
{ "_id" : ObjectId("5e350388fdf09dd6d08539c5"), "Status" : 40 }
{ "_id" : ObjectId("5e35038afdf09dd6d08539c6"), "Status" : 50 }

Here is the query to MongoDB group by −

> db.demo149.aggregate([
...    {
...       "$group": {
...          "_id": null,
...          "done": {
...             "$push": {
...                "$cond": [
...                   { "$eq": [ "$Status", 40 ] },
...                   { "_id": "$_id", "Status": "$Status" },
...                   false
...                ]
...             }
...          },
...          "notdone": {
...             "$push": {
...                "$cond": [
...                   { "$eq": [ "$Status", 50 ] },
...                   { "_id": "$_id", "Status": "$Status" },
...                   false
...                ]
...             }
...          }
...       }
...    },
... {
...    "$project": {
...       "_id": 0,
...       "done": {
...          "$setDifference": [ "$done", [false] ]
...       },
...       "notdone": {
...          "$setDifference": [ "$notdone", [false] ]
...          }
...       }
...    }
... ]);

This will produce the following output −

{
   "done" : [
      { "_id" : ObjectId("5e350386fdf09dd6d08539c4"), "Status" : 40 },
      { "_id" : ObjectId("5e350388fdf09dd6d08539c5"), "Status" : 40 } ], "notdone" : [
      { "_id" : ObjectId("5e35038afdf09dd6d08539c6"), "Status" : 50 }
   ]
}

Updated on: 31-Mar-2020

78 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements