日期:2014-05-16  浏览次数:20459 次

MongoDB 索引的命令 Index-Related Commands

?

索引的 命令

创建索引

ensureIndex() ?是创建索引便捷方法。 它的实现其实就是创建一个索引添加到system.indexes这个collection中。

> use test
> db.myCollection.ensureIndex(<keypattern>);
> // same as:
> db.system.indexes.insert({ name: "name", ns: "namespaceToIndex",?? ? key: <keypattern> });

注意: 一旦你创建了索引,所有插入collection的document像已存在的doucment一样会被索引。如果collection非常大,创建索引的时间可能会非常长并且会阻塞其他的操作。然而1.32版本,可以在后台执行这个过程。具体看如下连接?background indexing docs ?。

你可以查询system.indexes来查看当前db test的collection上的索引。

? >db.system.indexes.find( { ns: "test.foo" } );

一些驱动,如果最近调用过ensureIndex(),它会进行记录并且不会执行这个插入操作。In some drivers,? ensureIndex() ?remembers if it has recently been called, and foregoes the insert operation in that case. ensureIndex是个轻量的操作 ,因此它可以经常被调用,来保证索引的存在。

删除索引

Shell命令

db.mycollection.dropIndex(<name_or_pattern>)
db.mycollection.dropIndexes()
// example:t.dropIndex( { name : 1 } );

驱动

{ deleteIndexes: <collection_name>, index: <index_name> }
// <index_name>添加通配符*会删除所有的索引,除了_id。

索引的命名空间Index Namespace

每个索引都有自己的命名空间。如下

<collectionnamespace>.$<indexname>

这是个内部的存储,不能进行查询。

?