Is there a way to specify a condition of "where document doesn't contain field" ?

For example, I want to only find the first of these 2 because it doesn't have the "price" field.

{"fruit":"apple", "color":"red"}


{"fruit":"banana", "color":"yellow", "price":"2.00"}
share|improve this question
    
Possible duplicate of Mongo: find items that don't have a certain field – Ram Patra Nov 29 '15 at 8:28
2  
You can also try db.mycollection.find({ "price" : null }) – evilReiko Nov 13 '16 at 9:45
up vote 219 down vote accepted

Try the $exists operator:

db.mycollection.find({ "price" : { "$exists" : false } })

and see its documentation.

share|improve this answer
6  
+1. However, keep in mind that such queries can't use indexing and might be very slow on large collections. – mnemosyn Dec 19 '11 at 21:12
7  
Great point -- thanks. I know this caveat holds true in MongoDB version 1.8.x and before; but I thought queries with $exists field constraints can now make use of indexes in version 2.0 ...? – dampier Dec 20 '11 at 1:57
5  
Indeed - they can. Thanks! Seems I wasn't up to date. – mnemosyn Dec 20 '11 at 7:54

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.