Mongodb query - apply condition only if field exists

大城市里の小女人 提交于 2020-01-13 09:11:47

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!