MongoDB-按内部文档分组并检索最佳结果

时间:2019-09-08 19:20:36

标签: mongodb mongoose

我试图找到存储在mongo数据库中的最常见(和最不常见)的技能。我正在使用猫鼬来检索结果。

User是根文档,每个文档都有一个内部Profile文档。配置文件具有“技能”属性,其中包含ProfileSkillEntry数组,其中包含title(技能名称)。

return User.aggregate([{
        $group: {
            '_id': '$profile.skills.title',
            'count': {
                $sum: 1
            }
        }
    }, {
        $sort: {
            'count': -1
        }
    }, {
        $limit: 5
    }]);

我希望它可以将所有注册的User技能结合在一起,找到发生的前5名并将其返回。相反,它似乎是按用户分组并给出无效结果。

示例User文档结构:

{
    "_id" : ObjectId("..."),
    "firstName" : "Harry",
    "lastName" : "Potter",
    "profile" : {
        "_id" : ObjectId("..."),
        "skills" : [
            {
                "_id" : ObjectId("..."),
                "title" : "Java",
                "description" : "Master",
                "dateFrom" : "31/07/2019",
                "coreSkill" : true
            },
            {
                "_id" : ObjectId("..."),
                "title" : "JavaScript",
                "description" : "Proficient",
                "dateFrom" : "31/07/2019",
                "coreSkill" : false
            }
        ],
    }
}

1 个答案:

答案 0 :(得分:0)

请使用以下查询。只需根据您的要求添加排序和限制

db.test.aggregate(
[{ $unwind: {  path: "$profile.skills"} }, 
{ $group: {  _id: "$profile.skills.title",  
    "count": {    $sum: 1  }} }] )