【问题标题】:Python PyMongo Count Occurrences of Array ItemPython PyMongo 计数数组项的出现次数
【发布时间】:2017-12-08 06:28:57
【问题描述】:

我需要计算的值是一个值数组,因此不是 $myField 是项目的键,而是我需要计算的数组元素是所有文档中玉米、小麦、大麦的数量。

"myField": [
  "corn",
  "wheat"
],

这是单品的代码:

for result in c.aggregate([{
    "$group": {
        "_id": "$myField",
        "count": {"$sum": 1}
    }
}]):
    print("%s: %d" % (result["_id"], result["count"]))

【问题讨论】:

    标签: python arrays mongodb pymongo


    【解决方案1】:

    现在是 $unwind 的时候了,它将一个值数组转换为一系列文档,每个文档在数组所在的位置都有一个值:

    c = MongoClient().test.collection
    c.delete_many({})
    c.insert_many([
        {"myField": ["corn", "wheat"]},
        {"myField": ["corn", "barley"]},
        {"myField": ["hops"]},
    ])
    
    for result in c.aggregate([{
        "$unwind": "$myField"
    }, {
        "$group": {
            "_id": "$myField",
            "count": {"$sum": 1}
        }
    }]):
        print("%s: %d" % (result["_id"], result["count"]))
    

    输出:

    barley: 1
    wheat: 1
    hops: 1
    corn: 2
    

    【讨论】:

    猜你喜欢
    • 2014-03-18
    • 2022-12-07
    • 1970-01-01
    • 2014-10-16
    • 2016-01-19
    • 2015-06-18
    • 1970-01-01
    相关资源
    最近更新 更多