ChatGPT解决这个技术问题 Extra ChatGPT

MongoDB: Find a document by non-existence of a field?

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"}
You can also try db.mycollection.find({ "price" : null })

f
fracz

Try the $exists operator:

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

and see its documentation.


+1. However, keep in mind that such queries can't use indexing and might be very slow on large collections.
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 ...?