Pymongo, query on list field, and/or

眉间皱痕 提交于 2020-06-07 13:45:14

问题


I have a collection with some documents like:

{
    _id: 5,
    vals: [100, 1100, 1500]
},
{
    _id: 10,
    vals: [1100, 1700]
}

How can I query for documents that have, in vals field:

  • 1100
  • 1700 OR 100
  • 100 AND 1100

I can use some comprehension magic like:

g = lambda codes: (
    d for d in collection.find() if any(code in d["vals"] for code in codes)
)
g([100, 1700]).next()

Or, for the AND:

g = lambda codes: (
    d for d in collection.find() if all(code in d["vals"] for code in codes)
)
g([100, 1100]).next()

This seems a little clunky though if there is some find magic that can be done with the driver.


回答1:


yourmongocoll.find({"vals":1100})
yourmongocoll.find({"$or":[ {"vals":1700}, {"vals":100}]})
yourmongocoll.find({"$and":[ {"vals":100}, {"vals":1100}]})

i would recommend reading Mongodb Advanced queries

you will also find $in ...useful



来源:https://stackoverflow.com/questions/12064764/pymongo-query-on-list-field-and-or

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