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" } }