200

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"}
k00k
  • 17,314
  • 13
  • 59
  • 86
  • 1
    Possible duplicate of [Mongo: find items that don't have a certain field](http://stackoverflow.com/questions/5719408/mongo-find-items-that-dont-have-a-certain-field) – Ram Patra Nov 29 '15 at 08:28
  • 3
    You can also try `db.mycollection.find({ "price" : null })` – evilReiko Nov 13 '16 at 09:45

1 Answers1

373

Try the $exists operator:

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

and see its documentation.

fracz
  • 20,536
  • 18
  • 103
  • 149
dampier
  • 4,996
  • 1
  • 21
  • 18
  • 13
    +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
  • 11
    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 01:57