【问题标题】:How to get the value repetition count on array of objects for all entries on mongodb aggregation如何获取mongodb聚合上所有条目的对象数组的值重复计数
【发布时间】:2019-07-13 01:58:35
【问题描述】:

我有这样的数据结构:

{
    "_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);

非常感谢任何帮助

【问题讨论】:

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


    【解决方案1】:

    你可以$unwindassets,然后再申请$group with count:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-06-03
      • 1970-01-01
      • 2020-08-20
      • 1970-01-01
      • 2020-11-11
      • 1970-01-01
      • 2015-06-16
      相关资源
      最近更新 更多