【发布时间】: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 作为整个对象的问题计数。
【问题讨论】: