![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
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
Add a boolean field true to returned objects, when a specified value is in array. For NULL\nor other values, set false.
For this, use $ifNull. It evaluates an expression and returns the value of the expression if the expression evaluates to a non-null value. Let us first create a collection with documents −
> db.demo542.insertOne({"ListOfName":["Chris","David"]});{ "acknowledged" : true, "insertedId" : ObjectId("5e8cabc6ef4dcbee04fbbc17") } > db.demo542.insertOne({"ListOfName":null});{ "acknowledged" : true, "insertedId" : ObjectId("5e8cabc8ef4dcbee04fbbc18") } > db.demo542.insertOne({"ListOfName":["David"]});{ "acknowledged" : true, "insertedId" : ObjectId("5e8cabd3ef4dcbee04fbbc19") } > db.demo542.insertOne({"Name":"John"});{ "acknowledged" : true, "insertedId" : ObjectId("5e8cabdaef4dcbee04fbbc1a") }
Display all documents from a collection with the help of find() method −
> db.demo542.find();
This will produce the following output −
{ "_id" : ObjectId("5e8cabc6ef4dcbee04fbbc17"), "ListOfName" : [ "Chris", "David" ] } { "_id" : ObjectId("5e8cabc8ef4dcbee04fbbc18"), "ListOfName" : null } { "_id" : ObjectId("5e8cabd3ef4dcbee04fbbc19"), "ListOfName" : [ "David" ] } { "_id" : ObjectId("5e8cabdaef4dcbee04fbbc1a"), "Name" : "John" }
Following is the query to check for specific value −
> var id = "David"; > db.demo542.aggregate([ ... { ... "$project": { ... "matched": { ... "$eq": [ ... { ... "$size": { ... "$ifNull": [ ... { "$setIntersection": [ "$ListOfName", [id] ] }, ... [] ... ] ... } ... }, ... 1 ... ] ... } ... } ... } ... ])
This will produce the following output −
{ "_id" : ObjectId("5e8cabc6ef4dcbee04fbbc17"), "matched" : true } { "_id" : ObjectId("5e8cabc8ef4dcbee04fbbc18"), "matched" : false } { "_id" : ObjectId("5e8cabd3ef4dcbee04fbbc19"), "matched" : true } { "_id" : ObjectId("5e8cabdaef4dcbee04fbbc1a"), "matched" : false }
Advertisements