用于查询和排序的Mongodb复合索引

juud5qan  于 2022-12-18  发布在  Go
关注(0)|答案(1)|浏览(181)

我想使用这个查询:

db.getCollection("collection").find({ 
    ownerId: ObjectId('63983ccaee2908fb7490fc6c'), 
    status: { $ne: 'REJECTED' }, 
    username: { $regex: 'a', $options: 'i' } }
).sort({ role: 1, username: 1 });

什么是正确的复合索引?我使用这个索引:

LeagueUserSchema.index({ username: 'text' });

LeagueUserSchema.index({
  ownerId: 1,
  status: 1,
  role: 1,
  username: 1,
});

但通过 explain 我看到了这个:

"winningPlan" : { "stage" : "FETCH", "inputStage" : { "stage" : "SORT", "sortPattern" : { "role" : 1.0 }, "memLimit" : 3.3554432E7, "limitAmount" : 10.0, "type" : "default", "inputStage" : { "stage" : "IXSCAN", "filter" : { "username" : { "$regex" : "a", "$options" : "i" } }, "keyPattern" : { "leagueId" : 1.0, "userId" : 1.0, "status" : 1.0, "role" : 1.0, "username" : 1.0 }, "indexName" : "leagueId_1_userId_1_status_1", "isMultiKey" : false, "multiKeyPaths" : { "leagueId" : [  ], "userId" : [  ], "status" : [  ], "role" : [  ], "username" : [  ] }, "isUnique" : false, "isSparse" : false, "isPartial" : false, "indexVersion" : 2.0, "direction" : "forward", "indexBounds" : { "leagueId" : [ "[ObjectId('63983ccaee....

vlf7wbxs

vlf7wbxs1#

explain输出显示,用于该查询的索引不是您提到的索引,而是:

{
 "leagueId" : 1, 
 "userId" : 1, 
 "status" : 1, 
 "role" : 1, 
 "username" : 1 
}

在mongosh中检查以确保您提到的索引确实存在。
如果是,请运行explain并使用“allPlansExecution”选项,以便比较索引的性能。

相关问题