Indexing in MongoDB

Indexing is a necessary operation in MongoDB which brings efficiency in various execution of statements. In this chapter, you will learn about the concept of indexing and how it can be implemented in the MongoDB database.

What is indexing in MongoDB?

The concept of indexing is crucial for any database, and so for MongoDB also. Databases having indexes make queries performance more efficient. When you have a collection with thousands of documents and no indexing is done, your query will keep on finding certain documents sequentially. This would require more time to find the documents. But if your documents have indexes, MongoDB would restrict make it specific the number of documents to be searched within your collection.

Create an Index in MongoDB

In the MongoDB to create an index, the ensureIndex() method is used.

Syntax:
db.collection_name.ensureIndex( {KEY:1, KEY:2} )

Here in the above syntax, the key is a field name that you want to make an index and it will be 1 and -1 to make it on ascending or descending order.

Suppose we have the field name PhoneNo in the user's collection and you want to index it, then you have to type the syntax in this way:

Example:
db.Users.ensureIndex({"PhoneNo":1})

MongoDB ensureIndex method is Deprecated since version 3.0.0 and db.collection.ensureIndex() is now an alias for db.collection.createIndex().

Syntax:
db.collection_name.createIndex( {KEY:1, KEY:2} )
Example:
db.Users.createIndex({"PhoneNo":1})

Scroll Back to Top