首页 > 解决方案 > 如何编写高效的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);
                    })
                })
            })  
        })
    })

我们可以看到查询已经变得很长并且很难调试,我认为会很慢,我们可以优化它吗?你能至少指出我正确的方向吗?谢谢

标签: mongodb

解决方案


推荐阅读