Mongodb query - apply condition only if field exists

There is a way to make a query in such a way that if a certain field exists, it will apply a WHERE condition similar to that field, and if it passes, it will add this document to the result. If such a field does not exist, will it immediately add this document to the result?

+4
source share
1 answer

How about something like this:

db.stackoverflow.find({
  $or: [
    { howmuch: { $exists:false } },
    { howmuch:5 }
  ]})

In the stackoverflow collection, all documents that do not have a field howmuchplus all documents that are howmuchset to 5 will be found .

+14
source

Source: https://habr.com/ru/post/1536233/


All Articles