Python mongo-查找至少与值数组匹配的项
数据库条目:Python mongo-查找至少与值数组匹配的项,python,mongodb,pymongo,Python,Mongodb,Pymongo,数据库条目: {"item1": ["a", "b"], "item2":"etc"} {"item1": ["a", "b", "c"], "item2":"etc"} {"item1": ["a", "b", "c", "d", "e"], "item2":"etc"} 我想返回所有条目,其中a、b和c在item1数组中。它可以有附加值 {“item1”:{“$in”:[“a”、“b”、“c”]}查询返回是否找到任何数组项,这是不理想的 除了在$和块中嵌套$语句之外,还有更简单的方法吗 {
{"item1": ["a", "b"], "item2":"etc"}
{"item1": ["a", "b", "c"], "item2":"etc"}
{"item1": ["a", "b", "c", "d", "e"], "item2":"etc"}
我想返回所有条目,其中a
、b
和c
在item1数组中。它可以有附加值
{“item1”:{“$in”:[“a”、“b”、“c”]}
查询返回是否找到任何数组项,这是不理想的
除了在$和
块中嵌套$语句之外,还有更简单的方法吗
{"item1": {"$and" :[
{"$in" :["a"]},
{"$in" :["b"]},
{"$in" :["c"]},
]}}
不确定这是如何在pymongo操作方面快速提升的,但您可以始终执行以下操作
s = {'a', 'b', 'c'}
[e for e in entries if set(e['item1']).issubset(s)]
您不需要在
for item in col.find({"$and": [{"item1": 'a', "item1": 'b', "item1": 'c'}]}):
print(item)
输出
{'_id': ObjectId('54fa181014d995a397252a1a'), 'item1': ['a', 'b', 'c']}
{
'ok': 1.0,
'result': [
{
'_id': ObjectId('54fa181014d995a397252a1a'),
'item1': ['a', 'b', 'c'],
'is_subset': True
}
]
}
您还可以使用聚合管道和操作符
col.aggregate([{"$project": { "item1": 1, "is_subset": { "$setIsSubset": [ ['a', 'b', 'c'], "$item1" ] }}},{"$match": {"is_subset": True}}])
输出
{'_id': ObjectId('54fa181014d995a397252a1a'), 'item1': ['a', 'b', 'c']}
{
'ok': 1.0,
'result': [
{
'_id': ObjectId('54fa181014d995a397252a1a'),
'item1': ['a', 'b', 'c'],
'is_subset': True
}
]
}