简体   繁体   English

Pymongo,查询列表字段,和/或

[英]Pymongo, query on list field, and/or

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:如何查询在vals字段中具有以下内容的文档:

  • 1100 1100
  • 1700 OR 100 1700 或 100
  • 100 AND 1100 100 和 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:或者,对于 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.这似乎有点笨拙,但如果有一些可以通过驱动程序完成的查找魔法。

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我建议阅读Mongodb 高级查询

you will also find $in ...useful你还会发现$in ...有用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM