简体   繁体   中英

How to get the value repetition count on array of objects for all entries on mongodb aggregation

I have the data structure like this:

{
    "_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
        }
    ]
}

Now I want to implement the MongoDB aggregation by which I got the Answer like this:

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

I have to get this done by javascript but need to implement this on aggregation. My code for acheiveing with js is like this for set of array of object ie

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);

Any help is really appreciated

You can $unwind assets before applying $group with count:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM