簡體   English   中英

遍歷MongoDB聚集查詢產生的數組

[英]Iterating through array produced by MongoDB aggregation query

大家下午好

我在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值的運行總計中。

我對這里發生的事情不了解什么?

您無需使用應用程序邏輯來對數據進行分組,此任務進行了mongoDB聚合。 使用新字段將另一個$group添加到您的查詢中, All $sum將您的$num字段和$push所有文檔$push到一個名為categories的新字段中:

db.item.aggregate([{
    $group: {
        _id: "$category",
        num: { $sum: 1 }
    }
}, { $sort: { _id: 1 } }, {
    $group: {
        _id: 1,
        All: { $sum: "$num" },
        categories: {
            $push: {
                _id: "$_id",
                num: "$num"
            }
        }
    }
}])

它給 :

{
    "_id": 1,
    "All": 23,
    "categories": [{
        "_id": "Swag",
        "num": 2
    }, {
        "_id": "Office",
        "num": 2
    }, {
        "_id": "Stickers",
        "num": 2
    }, {
        "_id": "Apparel",
        "num": 6
    }, {
        "_id": "Umbrellas",
        "num": 2
    }, {
        "_id": "Kitchen",
        "num": 3
    }, {
        "_id": "Books",
        "num": 3
    }, {
        "_id": "Electronics",
        "num": 3
    }]
}

為了使用輸出, data是一個數組 ,使用data[0]來訪問第一個元素:

var categories = [];

database.collection("item").aggregate([{
    $group: {
        _id: "$category",
        num: { $sum: 1 }
    }
}, { $sort: { _id: 1 } }, {
    $group: {
        _id: 1,
        All: { $sum: "$num" },
        categories: {
            $push: {
                _id: "$_id",
                num: "$num"
            }
        }
    }
}]).toArray(function(err, data) {

    var totalCount = data[0]["All"];
    console.log("total count is " + totalCount);

    categories = data[0]["categories"];

    for (var i = 0; i < categories.length; i++) {
        console.log("category : " + categories[i]._id + " | count : " + categories[i].num);
    }
})

我想要實現的是推動或保持不變,我們稍后將看到一個類似以下內容的對象進入我的categories數組:

var allCategory = {
      _id: "All",
      num: [sum of all data.num values]
}

我最終.reduce()方法弄亂了,並在categories數組上使用了它。 我很幸運通過一些console.log -ing並最終做到了:

var categories = [];

    database.collection("item").aggregate([{
        $group : {
            _id : "$category",
             num : {$sum : 1}
         }},
        {$sort:{_id:1}}]).toArray(function(err, data){
            categories.push(...data);
            var sum = categories.reduce(function(acc, val){
                // console.log(acc, val["num"])
                return acc + val["num"]
            },0);

            var allCategory = {
                _id: "All",
                num: sum
            }
            categories.unshift(allCategory)
            callback(categories);
        })

首先,我使用散布運算符將data所有對象推入categories 然后聲明對categories運行.reduce() sum ,返回真正是data.numval["num"] data.num (控制台日志就是生命)。 我創建了allCategory文檔/對象,然后使用.unshift將其放在我的categories數組的開頭(此位置是.unshift ),然后使用回調。

我認為這是實現目標的一種簡單方法,我必須對.toArray()中方法和變量的正確順序進行一些試驗和錯誤。 然而它奏效了,我學到了一些東西。 感謝@Bertrand Martel的幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM