
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Push Computed Expression in a Group with MongoDB Query
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" ] }
Advertisements