Mongodb查找所有唯一列表元素的出现次数

时间:2019-06-18 10:52:43

标签: mongodb aggregation-framework pymongo

我在mongodb中具有以下数据:

{
  "name":["apple", "banana", "oranges", "grapes"]
},
{
  "name":["apple", "banana"]
},
{
  "name":["apple", "oranges"]
},
{
  "name":["oranges", "banana"]
},
{
  "name":["grapes", "banana"]
}

我要汇总并得到如下结果:-

{
  "apple": 3,
  "banana":4,
  "grapes": 3,
  "oranges": 3
}

我尝试过这样的事情:-

db.collection.aggregate([
            {"$unwind": "$name" },
            {"$group": {"_id":  "$name", "count": { "$sum": 1 }}}
        ]]

这将导致获得准确的数据,而某些独特元素会被遗漏。不知道我做错了什么。

1 个答案:

答案 0 :(得分:1)

您需要另一个$group才能将所有聚合合并到单个文档中,然后在其上运行$arrayToObject。另外,您可以使用$replaceRoot将新结构升级到根级别:

db.collection.aggregate([
    {"$unwind": "$name" },
    { $group: { _id: "$name", count: { $sum: 1 } } },
    { $group: { _id: null, names: { $push: { k: "$_id", v: "$count" } } } },
    { $replaceRoot: { newRoot: { $arrayToObject: "$names" } } }
])

Mongo Playground