Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you query for "is not null" in Mongo?

I would like to execute a following query:

db.mycollection.find(HAS IMAGE URL) 

What should be the correct syntax?

like image 336
TIMEX Avatar asked Oct 30 '10 04:10

TIMEX


People also ask

How do I make a field not null in MongoDB?

Basically, we can use the $exists a method to implement the not null in MongoDB. When <boolean> is valid, $exists coordinates with the records that contain the field, including reports where the field esteem is invalid. In case <boolean> is bogus, the question returns just the records that don't contain the field.

How do I search for null values in MongoDB?

The { item : null } query matches documents that either contain the item field whose value is null or that do not contain the item field. The query returns both documents in the collection.


2 Answers

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}) 
like image 96
Tim Gautier Avatar answered Oct 10 '22 10:10

Tim Gautier


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 } }); 
like image 22
Amitesh Bharti Avatar answered Oct 10 '22 10:10

Amitesh Bharti