问题
is there a way to make a query such that if certain field exists it will apply WHERE like condition on that field and if it pass will add that document to the result. If such field doesn't exist, it will immediately add that document to the result?
回答1:
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.
来源:https://stackoverflow.com/questions/23030328/mongodb-query-apply-condition-only-if-field-exists