Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb: $exists and $ne doesn't work together

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:

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

like image 773
Nattyk Avatar asked Sep 15 '25 18:09

Nattyk


1 Answers

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.

like image 104
DAXaholic Avatar answered Sep 18 '25 10:09

DAXaholic