在Mongodb上的复合索引上添加索引

Dea*_*nLa 3 indexing mongodb

我在db上创建了一个复合索引:

db.collection.ensureIndex({a:1,b:1})
Run Code Online (Sandbox Code Playgroud)

现在我意识到我需要另一个组成部分:

db.collection.ensureIndex({a:1,b:1,c:1})
Run Code Online (Sandbox Code Playgroud)

Mongodb会创建一个全新的索引,还是会知道修改现有索引?

Joh*_*yHK 5

ensureIndex使用不同字段调用将创建新索引.

您可以在运行这两个命令后使用getIndexes以查看集合中存在哪些索引来确认:

db.collection.getIndexes()
Run Code Online (Sandbox Code Playgroud)

如果您不再需要原始索引,可以使用以下命令删除它:

db.collection.dropIndex({a:1,b:1})
Run Code Online (Sandbox Code Playgroud)

  • 只是为了补充一点,索引`{a:1,b:1,c:1}`的行为就像`{a:1,b:1}`(除了支持`c`),因为[mongo]将使用索引前缀](http://docs.mongodb.org/manual/core/index-compound/#prefixes). (2认同)