Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find all docs where field doesn't exists, plus if field exists apply condition

Is there a way to make a query that:

  • if certain field exists, it will apply condition on the field and if it pass, it will add return document and add it to the results.
  • and if such field doesn't exist, it will also add document to the results?

In the end we will receive all documents where certain field have matched condition AND all document where such field doesn't exist at all.

like image 439
dakt Avatar asked Apr 12 '14 12:04

dakt


1 Answers

How about something like this:

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

In the stackoverflow collection, this will find all documents that do not have the howmuch field plus all documents that do have howmuch set to 5.

like image 125
John Petrone Avatar answered Oct 26 '22 19:10

John Petrone