

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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" } }
- Related Questions & Answers
- Ignore NULL and UNDEFINED values while running a MongoDB query
- Ignore first 4 values in MongoDB documents and display the next 3?
- Ignore null values in MySQL and display rest of the values
- Ignore NULL values from separate tables in a single MySQL query and display count of NOT NULL records
- Update values in multiple documents with multi parameter in MongoDB?
- MongoDB query to get distinct FirstName values from documents
- Sum the score of duplicate column values in MongoDB documents?
- Match MongoDB documents with fields not containing values in array?
- Check for existing documents/embedded documents in MongoDB
- MongoDB query for counting the distinct values across all documents?
- How to select documents with values above the average in MongoDB?
- Regex to ignore a specific character in MongoDB?
- MongoDB - Query embedded documents?
- Upsert many documents in MongoDB
- MongoDB query to find matching documents given an array with values?
Advertisements