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

2019-01-12 14:20发布

I would like to execute a following query:

db.mycollection.find(HAS IMAGE URL)

What should be the correct syntax?

8条回答
聊天终结者
2楼-- · 2019-01-12 14:51

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})
查看更多
欢心
3楼-- · 2019-01-12 15:05

the Query Will be

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

it will return all documents having "IMAGE URL" as a key ...........

查看更多
爷、活的狠高调
4楼-- · 2019-01-12 15:08

Sharing for future readers.

This query worked for us (query executed from MongoDB compass):

{
  "fieldName": {
    "$nin": [
      "",
      null
    ]
  }
}
查看更多
家丑人穷心不美
5楼-- · 2019-01-12 15:09

In pymongo you can use:

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

Because pymongo represents mongo "null" as python "None".

查看更多
SAY GOODBYE
6楼-- · 2019-01-12 15:09

One liner is the best :

db.mycollection.find({ 'fieldname' : { $exists: true, $ne: null } });

Here,

mycollection : place your desired collection name

fieldname : place your desired field name

Explaination :

$exists : When is true, $exists matches the documents that contain the field, including documents where the field value is null. If is false, the query returns only the documents that do not contain the field.

$ne selects the documents where the value of the field is not equal to the specified value. This includes documents that do not contain the field.

So in your provided case following query going to return all the documents with imageurl field exists and having not null value:

db.mycollection.find({ 'imageurl' : { $exists: true, $ne: null } });
查看更多
狗以群分
7楼-- · 2019-01-12 15:10
db.<collectionName>.find({"IMAGE URL":{"$exists":"true"}, "IMAGE URL": {$ne: null}})
查看更多
登录 后发表回答