很慢的mongo查询

时间:2014-07-07 13:23:01

标签: node.js mongodb mongoose

我在我的比赛中在node.js / moongose应用程序中得到了这样的模式。

var MatchSchema   = new Schema({
    race:       { type: Number, required: true},
    type:       { type: Number, required: true},
    path:       { type: Number, required: true},
    track:      { type: Number, required: true},
    players:    [{ type: Schema.Types.ObjectId, ref: 'Player', required: true }],
    scores:     [{ type: Schema.Types.ObjectId, ref: 'Score',  required: true }],
});

分数模型

var ScoreSchema   = new Schema({
    player:      { type: Schema.Types.ObjectId, ref: 'Player', required: true },
    match:       { type: Schema.Types.ObjectId, ref: 'Match',  required: true },
    score:       { type: Number, required: true},
});

我想查询数据库中特定曲目,路径,类型和播放器的最高分数。玩家字段是一系列ObjectId玩家。我这样知道:

// Find all matches of the right type, track, path for the player
Match.find( { path: path, track: track, players: {$in: [mongoose.Types.ObjectId(player)]}, type: type }, function(err, matches) {
    if(err || !matches) {
        // error handler...
    } else {
        var ids = matches.map(function(match) {
            return match._id;
        });
        // Find the scores from the matches and sort on score
        Score.aggregate([
            // match
            {
                "$match": { match: {$in: ids}}
            },
            // sort
            {
                "$sort": { score: -1 }
            },
            // skip
            {
                "$skip": skip
            },
            // limit
            {
                "$limit": limit
            }
        ], function(err, scores) {
            if (err || !scores) {
                // error handler
            } else {
                // do something cool
            }
        });
    }
});

但它极其缓慢,需要大约3秒才能找到匹配,1秒钟可以获得/并对分数进行排序。我在我的数据库中共获得了6000个匹配项,并从Matches.find()函数中获取了1000个文档。如何重新设计我的查询和/或我的模型以获得更好的性能。

0 个答案:

没有答案