计算每个元素中数组中的对象

时间:2017-09-20 19:30:56

标签: mongodb

我有这个人在mongodb的集合。     人员和每个人的名单都有一系列使用的语言

{ 
    "name" : "dev1", 
    "languages": [
        " java", 
        " python"
    ]
}
{ 
    "name" : "dev2", 
    "languages" : [
        "java", 
        "javascript"
    ]
}

I try to count the language used by the person, according to this JSON, the final output result expected will be :

{
    "java": 2,
    "python":1,
    "javascript": 1
}

Any idea to get that result with a mongoDB query ?

Many thanks

1 个答案:

答案 0 :(得分:0)

我假设您的问题中有拼写错误,并且数组中的值不包含任何其他空格。然后你可以使用

获得你想要的东西
collection.aggregate({
    $unwind: "$languages" // flatten the "languages" array
}, {
    $group: {
        "_id": "$languages", // group all occurrences of the same language into a bucket
        "count": { $sum: 1 } // count the occurrences per bucket
    }
})

这会给您以下结果:

/* 1 */
{
    "_id" : "javascript",
    "count" : 1.0
}

/* 2 */
{
    "_id" : "python",
    "count" : 1.0
}

/* 3 */
{
    "_id" : "java",
    "count" : 2.0
}

您可以在最后添加一些复杂的转换步骤以获得您想要的确切输出但我怀疑它是值得的:

collection.aggregate({
    $unwind: "$languages" // flatten the "languages" array
}, {
    $group: {
        "_id": "$languages",
        "count": { $sum: 1 }
    }
}, {
    $group: {
        "_id": null, // group by hardcoded _id in order to merge all documents
        "temp": { $push: { "k": "$_id", "v": "$count" } } // create an array that matches the structure that the $arrayToObject stage expects
    }
}, {
    $project: {
        temp: {
            $arrayToObject: "$temp" // transform key value pair array into object
        }
    }
}, {
    $replaceRoot: { newRoot: "$temp" } // replace root element with our final result
})

这会给你:

/* 1 */
{
    "javascript" : 1.0,
    "python" : 1.0,
    "java" : 2.0
}