我有这个MongoDB架构Buzzer
{
"_id": {
"$oid": "56cd9c103ff0020300fa1135"
},
"title": "50x kliky",
"timing": "2x týdně",
"user": "Stejk",
"history": [
{
"title": "50x kliky",
"datum": "11.09.2016",
"done": false
},
{
"title": "50x kliky",
"datum": "11.09.2016",
"done": true
},
{
"title": "50x kliky",
"datum": "11.09.2016",
"done": true
},
{
"title": "50x kliky",
"datum": "11.09.2016",
"done": true
},
{
"title": "50x kliky",
"datum": "11.09.2016",
"done": true
}
],
"__v": 0
}
我希望得到完成的数组。怎么做,我完全失去了。我现在不知道如何让它发生。请帮助。
非常感谢您的帮助
答案 0 :(得分:0)
请尝试通过以下aggregation
进行操作。
Buzzer.aggregate([
// unwind the history array
{$unwind: '$history'},
// filter the done field is true document
{$match: {'history.done': true}},
// count the result
{$group: {_id: '$_id', count: {$sum: 1}}}
], function(err, doc) {
});
答案 1 :(得分:0)
在普通的Javascript中,您可以使用Array#reduce
:
var data = { "_id": { "$oid": "56cd9c103ff0020300fa1135" }, "title": "50x kliky", "timing": "2x týdne", "user": "Stejk", "history": [{ "title": "50x kliky", "datum": "11.09.2016", "done": false }, { "title": "50x kliky", "datum": "11.09.2016", "done": true }, { "title": "50x kliky", "datum": "11.09.2016", "done": true }, { "title": "50x kliky", "datum": "11.09.2016", "done": true }, { "title": "50x kliky", "datum": "11.09.2016", "done": true }], "__v": 0 },
count = data.history.reduce(function (r, a) {
return r + a.done;
}, 0);
document.write(count);
答案 2 :(得分:0)
还有另外一个问题。怎么做到这一点。 (看评论)
BuzzerListekSchema.statics.getBuzzerListekDetailPercentage = function(req, response, res){
// Function1
this.aggregate([
{$unwind: '$history'},
{$match: {'history.done': true}}, //Filtr
{$group: {_id: req.params.id, count: {$sum: 1}}}
], function(err, c){
if(err){
res.status(500).json({succes: false, msg: 'Error'});
}
else {
// Here is result c
// {_id: ubuiabiufbuiab, count: 5}
}
});
// Function2
this.aggregate([
{$unwind: '$history'},
{$group: {_id: req.params.id, count: {$sum: 1}}}
], function(err, c){
if(err){
res.status(500).json({succes: false, msg: 'Error'});
}
else {
// Here is result c
// {_id: ubuiabiufbuiab, count: 5}
}
});
//Here i want reach a percent of percent=Function1/(Function2/100) and send it by JSON
//res.json({succes: false, msg: percent});
};