Say I have following documents in myCollection:
/* 1 */
{
"_id" : ObjectId("57861717ae5cdd68414b22fc"),
"category" : " ",
"name" : "Category is a space"
}
/* 2 */
{
"_id" : ObjectId("57861728ae5cdd68414b22fd"),
"category" : null,
"name" : "Category is null"
}
/* 3 */
{
"_id" : ObjectId("5786173dae5cdd68414b22fe"),
"name" : "Category is a not present"
}
/* 4 */
{
"_id" : ObjectId("57861755ae5cdd68414b22ff"),
"category" : "value",
"name" : "Category has value"
}
I want to query the document that has category field and the value is not null or not blank.
I tried the below queries:
With $exists
and two $ne
db.myCollection.find({"category":{"$exists":true}, "category":{"$ne":null}, "category":{"$ne":" "}})
I got 3 documents for this.
/* 1 */
{
"_id" : ObjectId("57861728ae5cdd68414b22fd"),
"category" : null,
"name" : "Category is null"
}
/* 2 */
{
"_id" : ObjectId("5786173dae5cdd68414b22fe"),
"name" : "Category is a not present"
}
/* 3 */
{
"_id" : ObjectId("57861755ae5cdd68414b22ff"),
"category" : "value",
"name" : "Category has value"
}
With $exists
and $ne=null
db.myCollection.find({"category":{"$exists":true}, "category":{"$ne":null}})
I got 2 documents for this.
/* 1 */
{
"_id" : ObjectId("57861717ae5cdd68414b22fc"),
"category" : " ",
"name" : "Category is a space"
}
/* 2 */
{
"_id" : ObjectId("57861755ae5cdd68414b22ff"),
"category" : "value",
"name" : "Category has value"
}
Finally I tried with $exists
and two $ne
enclosed in $and
db.myCollection.find({"category":{"$exists":true}, "$and":[{"category":{"$ne":null}}, {"category":{"$ne":" "}}]})
Only this gave the desired output:
/* 1 */
{
"_id" : ObjectId("57861755ae5cdd68414b22ff"),
"category" : "value",
"name" : "Category has value"
}
Now that I got my desired result, I want to understand whats wrong with the other two queries, particularly the first one.
From the docs
MongoDB provides an implicit AND operation when specifying a comma separated list of expressions. Using an explicit AND with the $and operator is necessary when the same field or operator has to be specified in multiple expressions.
So your first query uses the same field multiple times and the second query simply does not filter out the blank value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With