Mongodb Aggregate nested subdocuments

萝らか妹 提交于 2019-12-04 19:16:07

First you should get the totals for each 'user'. (i.e. { $group: {_id: '$user', count: {'$sum': 1} }})

Then just group by null to create a document with the result, add each user to set and push the result from first grouping onto array field. (2nd grouping)

db.test5.aggregate(
  { $unwind: "$elements" },
  { $unwind: "$elements.votes.meta" },
  { $project: {_id: '$_id', user: '$elements.votes.meta.createdBy'} },
  { $group: {_id: '$user', count: {'$sum': 1} }},
  { $group: {
        _id: null, 
        users: {$addToSet: '$_id'}, 
        occurances: {$push: {'user': '$_id', count: '$count'}}
        }
   }
)

Result:

{
    "result" : [ 
        {
            "_id" : null,
            "users" : [ 
                "545ab39ef1b0c88a695fcf8d", 
                "545aaddcf1b0c88a695fcf84", 
                "5461c0e2c9c39a192c44226c"
            ],
            "occurances" : [ 
                {
                    "user" : "5461c0e2c9c39a192c44226c",
                    "count" : 2
                }, 
                {
                    "user" : "545aaddcf1b0c88a695fcf84",
                    "count" : 2
                }, 
                {
                    "user" : "545ab39ef1b0c88a695fcf8d",
                    "count" : 2
                }
            ]
        }
    ],
    "ok" : 1
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!