In this tutorial, we'll focus on working with indexes in MongoDB. MongoDB uses indexes to quickly locate specific documents in a collection. Without indexes, MongoDB must scan the whole collection (a full collection scan) to find the documents that match a query. This can be slow for large collections.
By the end of this tutorial, you will learn:
- What is an index in MongoDB
- How to create, manage, and delete indexes in MongoDB
Prerequisites:
- Basic understanding of databases and MongoDB.
- MongoDB installed on your machine.
Indexes in MongoDB are similar to indexes in other database systems. MongoDB defines indexes at the collection level and supports indexes on any field or sub-field of the documents in a MongoDB collection.
You can create an index using the createIndex()
method, which has the following syntax:
db.collection.createIndex(keys, options)
keys
: The document that contains the field and direction of the index.options
: (Optional) The document that contains a set of options that controls the creation of the index.You can delete an index using the dropIndex()
method, which has the following syntax:
db.collection.dropIndex(indexName)
indexName
: The name of the index to be dropped.Suppose we have a users
collection, and we want to create an ascending index on the username
field. We can do this using the createIndex()
method.
db.users.createIndex({ "username": 1 })
The "1" in the { "username": 1 }
document specifies an ascending index. If you want to create a descending index, then you can use "-1".
Suppose we want to delete the index we created on the username
field. We can achieve this using the dropIndex()
method.
db.users.dropIndex("username_1")
The "1" in the "username_1" specifies that it is an ascending index. If it was a descending index, it would be "-1".
In this tutorial, we've learned:
- What an index in MongoDB is
- How to create and delete indexes in MongoDB
Next steps:
- Learn how to use the explain()
method to analyze query performance
- Learn about compound indexes and other types of indexes in MongoDB
Additional resources:
- MongoDB Indexes Documentation
email
field in the users
collection.username
and email
fields in the users
collection.email
field in the users
collection.db.users.createIndex({ "email": -1 })
db.users.dropIndex("email_-1")
username
and email
fields in the users
collection.db.users.createIndex({ "username": 1, "email": 1 })