MongoDB query to push a computed expression in a $group?


To push a computed expression in $group, use aggregate. Let us first create a collection with documents −

> db.demo24.insertOne({"Id":100,"Status":true});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e14c58722d07d3b95082e72")
}
> db.demo24.insertOne({"Id":100,"Status":true});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e14c58a22d07d3b95082e73")
}
> db.demo24.insertOne({"Id":100,"Status":false});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e14c58f22d07d3b95082e74")
}
> db.demo24.insertOne({"Id":100,"Status":true});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e14c59122d07d3b95082e75")
}
> db.demo24.insertOne({"Id":100,"Status":false});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e14c59222d07d3b95082e76")
}

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

> db.demo24.find();

This will produce the following output −

{ "_id" : ObjectId("5e14c58722d07d3b95082e72"), "Id" : 100, "Status" : true }
{ "_id" : ObjectId("5e14c58a22d07d3b95082e73"), "Id" : 100, "Status" : true }
{ "_id" : ObjectId("5e14c58f22d07d3b95082e74"), "Id" : 100, "Status" : false }
{ "_id" : ObjectId("5e14c59122d07d3b95082e75"), "Id" : 100, "Status" : true }
{ "_id" : ObjectId("5e14c59222d07d3b95082e76"), "Id" : 100, "Status" : false }

Here is the query to push (using $push) a computed expression in a $group −

> db.demo24.aggregate({$group: {_id:'$Id', AllValues: {$push: {$cond: [{$eq: ['$Status', true]},'Active','InActive']}}}})

This will produce the following output −

{ "_id" : 100, "AllValues" : [ "Active", "Active", "InActive", "Active", "InActive" ] }

Updated on: 02-Apr-2020

159 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements