How to create an index on a MongoDB collection

17 May,2021 by Rambler

Question: How do I create an index on a MongoDB ? I'd like to create it as a background activity - which will avoid disabling the database activity

 

Answer:  Find a sequence of statements supporting indexes . MongoDB indexes is a large topic , the commands below are just an introductory level. 

--list the collections on a database

db.getCollectionInfos();

--listing current indexes on a specific collection

db.collection_name.getIndexes();

--read rows in a collection

db.collection_name.find();

--create an index

**This is an example of creating a wildcard index . Check MongoDB documentation for create index and the various parameters.

**This example creates a wildcard index , running as a background task , also adding the parameters numIndexesBefore & numIndexesAfter

db.collection_name.createIndex( {"name.$**" : 1 }, { "background": true , "numIndexesBefore":1, "numIndexesAfter":2,"ok":1); 

--drop an index 

db.collection_name.dropIndex("name.$**_1")

 

Read more about MongoDB 

Quick Access To Mongodb Commands Cheat Sheet -

MongoDB Performance Tuning -


Author: Rambler (http://www.dba-ninja.com)


Share:

Verify your Comment

Previewing your Comment

This is only a preview. Your comment has not yet been posted.

Working...
Your comment could not be posted. Error type:
Your comment has been posted. Post another comment

The letters and numbers you entered did not match the image. Please try again.

As a final step before posting your comment, enter the letters and numbers you see in the image below. This prevents automated programs from posting comments.

Having trouble reading this image? View an alternate.

Working...

Post a comment on How to create an index on a MongoDB collection


dba-ninja.com