を使用される言語の配列を持っている私は、あなたの質問にタイプミスを持っていると仮定していると、あなたの配列内の値は、追加のスペースを含めることはできません。
が
/* 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", // group all occurrences of the same language into a bucket
"count": { $sum: 1 } // count the occurrences per bucket
}
})
使用して欲しいものを得ることができます
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
}
を、それはそれだけの価値だと疑い
ありがとう!まさに私が必要なものです – hmo