简体   繁体   English

pymongo 查询中的理解列表

[英]comprehension list in pymongo query

Good morning everyone,大家,早安,

I would like to write a pymongo snippet to query from a database all documents having a specific field value within a given list (so also a value which is a subset of any element in the given list).我想编写一个 pymongo 片段来从数据库中查询在给定列表中具有特定字段值的所有文档(因此也是给定列表中任何元素的子集的值)。

Within python, I would have two lists and I would like to find all elements from list one which are contained in at least one element from list two.在 python 中,我有两个列表,我想从列表一中找到包含在列表二中至少一个元素中的所有元素。 Eg:例如:

list1 = ['abc', 'bob', 'joe_123']
list2 = ['abc', 'joe', 'mike']
for string in list2:
    print( string, any([ string in xxx for xxx in list1 ]) )

which gives the correct result:这给出了正确的结果:

abc True
joe True
mike False

How could I get the same from pymongo?我怎么能从 pymongo 得到同样的东西? I tried the "$in" operator, but the result is not complete.我尝试了“$in”运算符,但结果不完整。

from pymongo import MongoClient
from pprint import pprint

client = MongoClient('mongodb://localhost:27017')
db = client['test_query']
my_coll = db['test_collection']

list1 = ['abc', 'bob', 'joe_123']
list2 = ['abc', 'joe', 'mike']

for string in list2:
    my_coll.insert_one({'string' : string})

cursor = my_coll.find({'string' : { '$in' : list1} })
which misses the case in joe < joe_123

pprint([c for c in cursor])
[{'_id': ObjectId('5f60ce9b682ff1bf4dcafb94'), 'string': 'abc'}]

Could anyone give me a hint on this?谁能给我一个提示?

More generally, what is the syntax to incorporate a python comprehension list into a pymongo query?更一般地说,将 python 理解列表合并到 pymongo 查询中的语法是什么?

Thank you so much非常感谢

Marco马可

$in in mongodb does not match on a partial string. mongodb 中的$in与部分字符串不匹配。

To do this you must use $regex , eg为此,您必须使用$regex ,例如

for string in list1:
    my_coll.insert_one({'string' : string})

query = {'$regex': '|'.join(list2)}
cursor = my_coll.find({'string' : query})

pprint([c for c in cursor])

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

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