[英]MongoDB: Aggregate values of all fields of a specific subdocument
我正在嘗試使用MongoDB的聚合框架從具有以下結構的集合生成文檔:
{
"_id" : ObjectId("5510eb56f877bbef153d236d"),
"attributes" : {
"brand" : "Mercedes",
"price" : 289,
"family" : "GARDEN"
},
"name" : "Bigger Fix Soft Crisps"
}
{
"_id" : ObjectId("5510eb56f877bbef153d236e"),
"attributes" : {
"brand" : "Adelholzener",
"price" : 683,
"family" : "COMPUTER"
},
"name" : "Soft Stockhome Chips"
}
{
"_id" : ObjectId("5510eb56f877bbef153d236f"),
"attributes" : {
"brand" : "Pepsi",
"price" : 789,
"family" : "CAR"
},
"name" : "Light Yearsailfresh Meat"
}
我想從attributes
子文檔中獲取所有字段的聚合及其可能的值。 由於子文檔中的字段未知,因此我不能簡單地使用此示例中給出的字段,因此必須是動態的。 結果看起來應該類似於:
{
"_id" : "brand",
"values" : [
"Mercedes", "Adelholzener", "Pepsi"
]
},
{
"_id" : "price",
"values" : [
289, 683, 789
]
},
{
"_id" : "family",
"values" : [
"GARDEN", "COMPUTER", "CAR"
]
}
到目前為止,我還沒有找到解決這個特殊問題的方法。 我嘗試使用$project
和$unwind
(這顯然只適用於數組)。
試圖找出如何做到聚合,但我不確定它是否可能,因為你無法以任何好的方式獲取對象中的鍵。
這是一個MapReduce工作,它完成了這件事:
db.runCommand({
"mapreduce" : "test_collection", // Change collection here
"map" : function() {
for (var key in this.attributes) {
// Emit objects w array as we cannot reduce arrays directly
emit(key, {x: [this.attributes[key]]});
}
},
"reduce" : function(key, values) {
var res = [];
values.forEach(function (d) {
Array.prototype.push.apply(res, d.x);
});
return {x: res};
},
"finalize": function (key, reducedVal) {
return reducedVal.x;
},
"out": { inline: 1 }
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.