Index bezogene Befehle

3. Create Index

ensureIndex() is the helper function for this. Its implementation creates an index by adding its info to the system.indexes table.

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

Note: Once you've inserted the index, all subsequent document inserts for the given collection will be indexed, as will all pre-existing documents in the collection. If you have a large collection, this can take a significant amount of time and will block other operations. However, beginning with version 1.3.2, you can specify that indexing happen in the background. See the [background indexing docs] for details.

You can query system.indexes to see all indexes for a table foo:

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

In some drivers, ensureIndex() remembers if it has recently been called, and foregoes the insert operation in that case.  Even if this is not the case, ensureIndex() is a cheap operation, so it may be invoked often to ensure that an index exists.

Dropping an Index

From the shell:

db.mycollection.dropIndex(<name_or_pattern>) 
db.mycollection.dropIndexes() 

// example: 
t.dropIndex( { name : 1 } ); 

From a driver (raw command object form; many drivers have helpers):

{ deleteIndexes: <collection_name>, index: <index_name> } 
// "*" for <index_name> will drop all indexes except _id 

Index Namespace

Each index has a namespace of its own for the btree buckets. The namespace is:

<collectionnamespace>.$<indexname>

This is an internal namespace that cannot be queried directly.


Enter labels to add to this page:
Please wait 
Looking for a label? Just start typing.

IF YOU HAVE A QUESTION, POST IT TO THE USER GROUP.

These pages are fine for comments, but for questions, your best bet will always be the MongoDB User Group.

blog comments powered by Disqus