2017-09-20 10 views
0

私はこの集団を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 

答えて

0

を使用される言語の配列を持っている私は、あなたの質問にタイプミスを持っていると仮定していると、あなたの配列内の値は、追加のスペースを含めることはできません。

/* 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 
} 
を、それはそれだけの価値だと疑い
+0

ありがとう!まさに私が必要なものです – hmo

関連する問題