我目前正在执行一项涉及编写一些查询的任务。我要获取的结果是这样的,Attacker_king就像被攻击的次数,而Defender_king像被防御的次数。
'most_active': {
'attacker_king': null,
'defender_king': null,
'region': null,
'name': null
},
'attacker_outcome': {
'win': null,
'loss': null
} }
我已经在MongoDB中编写了查询,就像这样
db.aggregate([
{$group: {
_id: "$attacker_king",
"count": {
$sum: 1
}
}},{
$sort:{"count":-1}
},{
$limit:1
}
], function (err, response) {
result.most_active.attacker_king = response[0]._id;
db.aggregate([
{$group: {
_id: "$defender_king",
"count": {
$sum: 1
}
}},{
$sort:{"count":-1}
},{
$limit:1
}
],function(err,response){
result.most_active.defender_king = response[0]._id;
db.aggregate([
{$group: {
_id: "$region",
"count": {
$sum: 1
}
}},{
$sort:{"count":-1}
},{
$limit:1
}
],function(err,response){
result.most_active.region = response[0]._id;
db.aggregate([
{$group: {
_id: "$name",
"count": {
$sum: 1
}
}},{
$sort:{"count":-1}
},{
$limit:1
}
],function(err,response){
result.most_active.name = response[0]._id;
//return res.send(result)
db.aggregate([
{$group: {
_id: "$attacker_outcome",
"count": {
$sum: 1
}
}},{
$sort:{"count":-1}
}
],function(err,response){
console.log(response)
result.attacker_outcome.win = response[0].count;
result.attacker_outcome.loss = response[1].count;
return res.send(result);
})
})
})
})
})
我们可以看到查询已经很长了,很难调试,我认为很慢,我们可以优化它吗?你至少能指出我正确的方向吗? 谢谢