I would like to execute a following query:
db.mycollection.find(HAS IMAGE URL)
What should be the correct syntax?
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.
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.
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})
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 } });
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