【问题标题】:how to find values that are common for different fields [pymongo aggregate]如何找到不同字段共有的值 [pymongo 聚合]
【发布时间】:2015-05-01 11:33:27
【问题描述】:

假设我们有 mongodb 文档:

{'shop':'yes'}
{'shop':'ice_cream'}
{'shop':'grocery'}
{'amenity':'yes'}
{'amenity':'hotel'}

如何在 pymongo 中编写一个聚合查询来返回两个键的共同值?在该示例中,它应该返回“是”。

【问题讨论】:

    标签: python mongodb aggregation-framework pymongo


    【解决方案1】:

    您的聚合管道将在 $project 运算符阶段使用 $setIntersection。这需要两个或多个数组并返回一个数组,其中包含出现在每个输入数组中的元素。另一个有用的聚合运算符是 $addToSet 数组运算符,它用于为每个分组字段创建不同的值列表,然后可以在以后进行比较。

    在 mongoshell 中,插入文档

    db.collection.insert([
        {'shop':'yes'},
        {'shop':'ice_cream'},
        {'shop':'grocery'},
        {'amenity':'yes'},
        {'amenity':'hotel'}
    ])
    

    您可以尝试以下聚合管道:

    db.collection.aggregate([
        {
            "$group": {
                "_id": null,
                "shops": {
                    "$addToSet": "$shop"
                },
                "amenities": {
                    "$addToSet": "$amenity"
                }
            }        
        },
        {
            "$project": {
                "_id": 0,
                "commonToBoth": { "$setIntersection": [ "$shops", "$amenities" ] }
            }
        }
    ]);
    

    输出

    /* 0 */
    {
        "result" : [ 
            {
                "commonToBoth" : [ 
                    "yes"
                ]
            }
        ],
        "ok" : 1
    }
    

    Pymongo

    >>> pipe = [
    ...     {"$group": { "_id": None, "shops": {"$addToSet": "$shop"}, "amenities": {"$addToSet": "$amenity"}}},
    ...     { "$project": {"_id": 0, "commonToBoth":{"$setIntersection": ["$shops", "$amenities"]}}}
    ...     ]
    >>>
    >>> for doc in collection.aggregate(pipe):
    ...     print(doc)
    ...
    {u'commonToBoth': [u'yes']}
    

    【讨论】:

      猜你喜欢
      • 2020-08-30
      • 1970-01-01
      • 2021-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-09
      • 2020-03-31
      • 1970-01-01
      相关资源
      最近更新 更多