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