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
Ignore null values in MongoDB documents
To ignore null values in MongoDB, use "$ne" : null in aggregate(). Let us create a collection with documents −
> db.demo722.insertOne(
... {
... id:101,
... details: [
... { Name:""},
... { Name: "David"},
... {Name:null},
... {Name:"Carol"}
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5eab07d543417811278f5889")
}
Display all documents from a collection with the help of find() method −
> db.demo722.find();
This will produce the following output −
{ "_id" : ObjectId("5eab07d543417811278f5889"), "id" : 101, "details" : [ { "Name" : "" }, { "Name" : "David" }, { "Name" : null }, { "Name" : "Carol" } ] }
Following is the query to ignore null values in MongoDB using $ne −
> db.demo722.aggregate([
... {"$unwind": "$details"},
...
... {"$match": { "details.Name" :{ "$ne" : null } } }
... ])
This will produce the following output −
{ "_id" : ObjectId("5eab07d543417811278f5889"), "id" : 101, "details" : { "Name" : "" } }
{ "_id" : ObjectId("5eab07d543417811278f5889"), "id" : 101, "details" : { "Name" : "David" } }
{ "_id" : ObjectId("5eab07d543417811278f5889"), "id" : 101, "details" : { "Name" : "Carol" } }Advertisements