【问题标题】:Count an array inside an array and then sum them MongoDB NodeJS计算一个数组中的一个数组,然后对它们求和 MongoDB NodeJS
【发布时间】:2016-06-28 17:05:53
【问题描述】:

我有一个包含页面对象数组的对象,每个页面对象都有一个问题数组。

Ex 对象:

{
Id: 1,
UserId: 14,
Deleted: false,
Collaborators: [],
Title: "Awesome",
Pages: [{
    Id: 1,
    Title: 'Jank',
    Questions: [
        { Id: 1, Content: 'Ask me about it' },
        { Id: 2, Content: 'Ask me about it again' }
    ]
}, {
    Id: 2,
    Title: 'Janker',
    Questions: [
        { Id: 1, Content: 'Tell me about it' },
        { Id: 2, Content: 'Tell me about it again' }
    ]
}]
}

我要做的是计算整个 bas 对象的所有问题。我不知道该怎么做。我尝试使用aggregate$sum 的总问题,然后对$sum 执行另一个函数,以获得整个对象的总数。不幸的是,我的$sum 并没有像我想象的那样工作。

Ex 代码(nodejs):

var getQuestionCount = function(id) {
    var cursor = mongo.collection('surveys').aggregate([{
            $match: {
                $or: [{
                    "UserId": id
                }, {
                    "Collaborators": {
                        $in: [id]
                    }
                }]
            }
        }, {
            $match: {
                "Deleted": false
            }
        }, {
            $unwind: "$Pages"
        },
        { $group: { _id: null, number: { $sum: "$Pages.Questions" } } }
    ], function(err, result) {
        //This log just gives me [object Object], [object Object]
        console.log('q count ' + result);
    });
}

知道怎么做吗?上面示例对象的最终结果理想情况下会返回 4 作为整个对象的问题计数。

【问题讨论】:

    标签: arrays node.js mongodb


    【解决方案1】:

    我会尝试以下 shell 查询。

    db.collection.aggregate([
      // filter out unwanted documents.
      {$match:{Id: 1}},
    
      // Unwind Pages collection to access Questions array
      {$unwind:"$Pages"},
    
      // Count items in Questions array
      {$project:{count: {$size:"$Pages.Questions"}}},
    
      // Finally sum items previously counted.
      {$group:{_id:"$_id", total: {$sum: "$count"}}}
    ])
    

    根据您的示例文档,它应该返回正确的问题数。

    { 
        "_id" : ObjectId("57723bb8c10c41c41ff4897c"), 
        "total" : NumberInt(4)
    }
    

    【讨论】:

    • 谢谢你做得很好。结果是一个数组,不是单个对象,所以我只是做了 result[0].total
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-22
    • 2019-03-11
    • 1970-01-01
    • 2020-07-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多