How do you query for “is not null” in Mongo?

后端 未结 10 2233
暖寄归人
暖寄归人 2020-11-30 15:59

I would like to execute a following query:

db.mycollection.find(HAS IMAGE URL)

What should be the correct syntax?

10条回答
  •  独厮守ぢ
    2020-11-30 16:52

    This will return all documents with a key called "IMAGE URL", but they may still have a null value.

    db.mycollection.find({"IMAGE URL":{$exists:true}});
    

    This will return all documents with both a key called "IMAGE URL" and a non-null value.

    db.mycollection.find({"IMAGE URL":{$ne:null}});
    

    Also, according to the docs, $exists currently can't use an index, but $ne can.

    Edit: Adding some examples due to interest in this answer

    Given these inserts:

    db.test.insert({"num":1, "check":"check value"});
    db.test.insert({"num":2, "check":null});
    db.test.insert({"num":3});
    

    This will return all three documents:

    db.test.find();
    

    This will return the first and second documents only:

    db.test.find({"check":{$exists:true}});
    

    This will return the first document only:

    db.test.find({"check":{$ne:null}});
    

    This will return the second and third documents only:

    db.test.find({"check":null})
    

提交回复
热议问题