我有这个MongoDB架构
{
"_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
}
我有这些代码
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});
};
我想用这些Function1 /(Function2 / 100)做出JSON响应。 有关更多说明,请参阅代码中的注释 如何通过这两个功能达到c? 请帮助,我们总共菜鸟,所以要耐心等待。 非常感谢。
答案 0 :(得分:0)
考虑运行以下管道以获得所需的结果:
BuzzerListekSchema.statics.getBuzzerListekDetailPercentage = function(req, response, res){
var id = req.params.id;
var pipeline = [
{ "$match": { "_id": id } },
{ "$unwind": "$history" },
{
"$group": {
"_id": 0,
"count": {
"$sum": {
"$cond": [
{ "$eq": [ "$history.done", true ] },
1,
0
]
}
},
"total": { "$sum": 1 }
}
},
{
"$project": {
"_id": 0,
"percentage":{
"$multiply": [
{ "$divide": [ 100, "$total" ] }, "$count"
]
}
}
}
]
this.aggregate(pipeline)
.exec(function (err, result){
if(err){
res.status(500).json({succes: false, msg: 'Error'});
}
else {
res.json({succes: false, msg: result[0]})
}
});
}
答案 1 :(得分:0)
解答谢谢@chridam
BuzzerListekSchema.statics.getBuzzerListekDetailPercentage = function(req, response, res){
var id = req.params.id;
var pipeline = [
{"$match": {"_id": mongoose.Types.ObjectId(id)}},
{ "$unwind": "$history" },
{
"$group": {
"_id": null,
"count": {
"$sum": {
"$cond": [
{ "$eq": [ "$history.done", true ] },
1,
0
]
}
},
"total": { "$sum": 1 }
}
},
{
"$project": {
"_id": 0,
"percentage":{
"$multiply": [
{ "$divide": [ 100, "$total" ] }, "$count"
]
}
}
}
];
this.aggregate(pipeline)
.exec(function (err, result){
if(err){
res.status(500).json({succes: false, msg: err});
}
else {
res.status(200).json({succes: true, msg: result[0]})
}
});
};