mongodb - 如何编写高效的mongodb查询?
问题描述
我目前正在执行一项任务,其中涉及编写一些查询。我想要获取的结果是,看起来像这样,attacker_king 就像被攻击的次数和 defer_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);
})
})
})
})
})
我们可以看到查询已经变得很长并且很难调试,我认为会很慢,我们可以优化它吗?你能至少指出我正确的方向吗?谢谢
解决方案
推荐阅读
- spring - 如何对子属性中包含的 ID 进行复杂的 @PreAuthorize 检查?
- rust - 具有可变引用的递归结构中的生命周期
- templates - 在生产站点中为 getTemplate lsit 调用 Docusign API 失败?
- rundeck - 有没有办法使用非登录用户来运行 Rundeck 作业?
- php - WampServer, mysqli_connect (HY000/1045) 拒绝用户访问
- javascript - 无法读取 null 的属性“角色”
- javascript - 从 HTML 输入中获取日期以在 JS 中使用
- mysql - 优化二级索引和日期范围查询
- scala - 尝试失败时的短路映射操作
- c# - 我的 NLog 记录没有保存。我在哪里可以看到我的 NLog 保存失败?