如何获取mongodb聚合上所有条目的对象数组上的值重复计数

时间:2019-02-19 14:18:25

标签: javascript node.js mongodb aggregation-framework aggregation

我有这样的数据结构:

{
    "_id" : ObjectId("5c4404906736bd2608e30b5e"),
    "assets": [ 
        {
            "name" : "xa",
            "id"   : 1
        },
        {
            "name" : "xs",
            "id"   : 2
        }
    ]
},
{
    "_id" : ObjectId("5c4404906736bd2608e30b5f"),
    "assets": [ 
        {
            "name" : "xa",
            "id"   : 3
        }
    ]
},
{
    "_id" : ObjectId("5c4404906736bd2608e30b5g"),
    "assets": [ 
        {
            "name" : "xa",
            "id"   : 4
        },
        {
            "name" : "xd",
            "id"   : 5
        },
        {
            "name" : "xs",
            "id"   : 6
        }
    ]
}

现在,我想实现MongoDB聚合,通过该聚合,我可以这样获得答案:

[
 {
  "assets": "xa",
  "count": 3
 },
 {
  "assets": "xs",
  "count": 2
 },
 {
  "assets": "xd",
  "count": 1
 },
]

我必须通过javascript完成此操作,但需要在聚合时实施。我用js实现的代码就是这样的一组对象数组,即

var arr = [
  { asset: "xa" },
  { asset: "xs" },
  { asset: "xa" },
  { asset: "xs" },
  { asset: "xa" },
  { asset: "xd" }
];

var userDict = arr.reduce((acc, el) => {
  if (!acc.hasOwnProperty(el.asset)) {
    acc[el.asset] = { count: 0 };
  }
  acc[el.asset].count++;
  return acc;
}, {});

var result = Object.entries(userDict).map(([k, v]) => ({
  asset: k,
  count: v.count
}));
console.log(result);

真的很感谢任何帮助

1 个答案:

答案 0 :(得分:2)

您可以$unwind assets,然后再应用带有计数的$group

db.col.aggregate([
    {
        $unwind: "$assets"
    },
    {
        $group: {
            _id: "$assets.name",
            count: { $sum: 1 }
        }
    },
    {
        $project: {
            _id: 0,
            asset: "$_id",
            count: 1
        }
    }
])