大家下午好,MongoDB聚合查詢生成的數組迭代
我在MongoDB 3.4中使用聚合查詢的時間非常艱難。我有一個要我做我的聚集查詢的結果推到一個名爲categories
空數組,我已經能夠使用此代碼成功地做了一個問題:
var categories = [];
database.collection("item").aggregate([{
$group : {
_id : "$category",
num : {$sum : 1}
}},
{$sort:{_id:1}}]).toArray(function(err, data){
categories.push(...data);
callback(categories);
console.log(categories);
})
}
categories
看起來是這樣的:
[ { _id: 'Apparel', num: 6 },
{ _id: 'Books', num: 3 },
{ _id: 'Electronics', num: 3 },
{ _id: 'Kitchen', num: 3 },
{ _id: 'Office', num: 2 },
{ _id: 'Stickers', num: 2 },
{ _id: 'Swag', num: 2 },
{ _id: 'Umbrellas', num: 2 } ]
接下來,我有以下任務:
In addition to the categories created by your aggregation query, include a document for category "All" in the array of categories passed to the callback. The "All" category should contain the total number of items across all categories as its value for "num". The most efficient way to calculate this value is to iterate through the array of categories produced by your aggregation query, summing counts of items in each category.
問題是,它看起來像在我的.toArray()
方法中,data
參數有時像一個數組,有時不起作用。例如,如果我想將num
鍵的值添加到categories
陣列中,如下所示:categories.push(...data["num"])
我收到一條錯誤消息,提示undefined is not iterable
。
由於我無法迭代每個data.num
密鑰,我無法提取它的值並將其添加到所有data.num
值的運行總計中。
我不理解這裏發生了什麼?
您的解決方案與我正在尋找的內容非常接近,我感謝您的回覆。我認爲,在你的意見之後,我更好地理解了我正在處理的事情。我唯一不清楚的就是需要在'data'數組中創建新的'{category:'All}'文檔部分,我會在你的下面發佈我的答案,這樣你就可以看到我要做什麼了。 – m00saca