- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Implement a MongoDB $cond field in a projection pipeline based on the presence or absence of a field?
For this, you can use $cond along with $anyElementTrue. NULL values (absence of a field) would evaluate to FALSE. With that, an empty array also returns FALSE with $ anyElementTrue.
Let us first create a collection with documents −
> db.presenceDemo.insertOne({"StudentName":null}); { "acknowledged" : true, "insertedId" : ObjectId("5e06f70c25ddae1f53b621f3") } > db.presenceDemo.insertOne({"StudentName":"Chris"}); { "acknowledged" : true, "insertedId" : ObjectId("5e06f71425ddae1f53b621f4") } > db.presenceDemo.insertOne({"StudentName":null}); { "acknowledged" : true, "insertedId" : ObjectId("5e06f71825ddae1f53b621f5") } > db.presenceDemo.insertOne({"StudentName":"David"}); { "acknowledged" : true, "insertedId" : ObjectId("5e06f71e25ddae1f53b621f6") }
Following is the query to display all documents from a collection with the help of find() method −
> db.presenceDemo.find();
This will produce the following output −
{ "_id" : ObjectId("5e06f70c25ddae1f53b621f3"), "StudentName" : null } { "_id" : ObjectId("5e06f71425ddae1f53b621f4"), "StudentName" : "Chris" } { "_id" : ObjectId("5e06f71825ddae1f53b621f5"), "StudentName" : null } { "_id" : ObjectId("5e06f71e25ddae1f53b621f6"), "StudentName" : "David" }
Here is the query to implement a $cond field based on the presence or absence of a field −
> db.presenceDemo.aggregate([ ... { "$project": { ... "MyValue": { ... "$cond": [ ... { "$anyElementTrue": [ [ "$StudentName" ] ] }, ... 1, ... 0 ... ] ... } ... }} ... ]);
This will produce the following output −
{ "_id" : ObjectId("5e06f70c25ddae1f53b621f3"), "MyValue" : 0 } { "_id" : ObjectId("5e06f71425ddae1f53b621f4"), "MyValue" : 1 } { "_id" : ObjectId("5e06f71825ddae1f53b621f5"), "MyValue" : 0 } { "_id" : ObjectId("5e06f71e25ddae1f53b621f6"), "MyValue" : 1 }
Advertisements