mongo - 查找至少匹配值数组的项目

时间:2015-03-06 20:56:20

标签: python mongodb pymongo

数据库条目:

{"item1": ["a", "b"], "item2":"etc"}
{"item1": ["a", "b", "c"], "item2":"etc"}
{"item1": ["a", "b", "c", "d", "e"], "item2":"etc"}

我想返回所有条目,其中abc位于item1数组中。它可以有其他值。

如果找到任何数组项,{"item1": {"$in" :["a", "b", "c"]}}查询将返回,这是不理想的。

除了在$in块中嵌套$and语句之外,还有更简单的方法吗?

{"item1": {"$and" :[
    {"$in" :["a"]},
    {"$in" :["b"]},
    {"$in" :["c"]},
]}}

2 个答案:

答案 0 :(得分:0)

不确定这在pymongo操作方面是如何快速进行的,但你可以随时执行以下操作......

s = {'a', 'b', 'c'}
[e for e in entries if set(e['item1']).issubset(s)]

答案 1 :(得分:0)

您无需使用$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
                   }
               ]
 }