How to Create Indexes in MongoDB: Examples Explained

As with any database, indexes are essential data structures in MongoDB. They foster easy database queries and let you store and arrange a part of your collection in unique fields. Indexes also support range querying without a hitch.

If your app uses MongoDB, you want to leverage the power of indexes to make your queries faster and more efficient. So what are indexes in MongoDB, and how can you create them?

What Are Indexes in MongoDB?

Indexes in MongoDB let you prioritize some fields in a document and turn them into query parameters later on. When creating a collection, MongoDB creates a default ID index. But you can add more if you have higher queries or arrangement needs.

Unique indexes also prevent duplicates during data entry. They come in handy for rejecting entries that already exist in the database. So you can use unique indexing on usernames and email fields, for instance.

Indexes help you grab specifically what you want using your defined query format at the required quantity without scanning an entire collection. When creating an index, you can specify how you want your data sorted whenever you query it.

For instance, if you decide to sort data points by their entry dates without using an index, you’ll typically provide query criteria and sort order.

Say you want to arrange ages higher than a certain number by their descending date of entries. Your query typically looks like this:

db.collectionName.find({age: {$gt: 50}}).sort({date: -1})

But if you had an index on the entry dates, you’d only need to provide the query criteria. This is so because you’d have already sorted the date descendingly while creating the index.

In that case, the above query becomes:

db.collectionName.find({age: {$gt: 50}})

How to Create an Index in MongoDB

You can create indexes in MongoDB using its built-in shell interface. So that’s what we’ll use in this tutorial.

Nevertheless, indexes don’t exist alone. You must’ve created a database and a collection before you can create an index.

As we previously mentioned, a prominent feature of indexing is that it lets you specify sorting criteria during index creation.

For example, an index that arranges age in a reverse order looks like this:

db.userCollection.createIndex({age: -1})

The negative integer (-1) in the code tells MongoDB to arrange age in a reverse order whenever you query data using the age index. Thus, you might not need to specify a sorting order during queries since the index handles that already.

To create an index of the same field ascendingly, replace -1 with 1:

db.userCollection.createIndex({age: 1})

Although there are other index types in MongoDB, this is how to create the single and compound forms—since they’re the most used.

But before we go on, ensure that you’ve set up a MongoDB server on your PC. If you’ve already done so, open the MongoDB shell and follow along.

Create a Single Index in MongoDB

Single indexing in MongoDB is straightforward. To start, select a database that already contains collections.

Say our database name is MUO:

use MUO

Once you choose a database, use the createIndex() command in the shell to create a single index.

For example, to create a single username index in a collection and use it to query in reverse order:

db.collectionName.createIndex({username: -1})

Multikey Indexing in MongoDB

Multikey indexes come in handy for indexing a field in a complex data array. For instance, a collection might contain complex data of users with their information in another array. For example, say name, height, and age.

You can create a multikey index on the height of each user in that array like this:

db.customers.createIndex({user.height: 1})

The height in the above code is a subset of the user field.

Create a Compound Index

A compound index contains more than one index. To create a compound index of address and product type on a customer collection, for instance:

db.customer.createIndex({address: 1, products: 1})

Since you didn’t provide a name while creating the above index, MongoDB creates one by default. But it separates the name of each index by an underscore. So it’s less readable, especially if you have more than two indexes in a compound.

To specify a name when creating a compound index:

db.customers.createIndex({location: 1, products: 1, weight: -1}, {name: "myCompundIndex"})

Get All Indexes in a Collection

To view all indexes in a collection:

db.collectionName.getIndexes()

The above code outputs all the indexes in a named collection.

Organize Your Database With Indexes

Indexing in MongoDB reduces runtime latency when executing concurrent queries. Plus, they help you organize your database and make it more accessible. As you’ve seen, creating indexes in MongoDB isn’t complex, after all. The examples here are enough to get you started with index creation. Nonetheless, to see your indexes in practice, you need to know how querying works in MongoDB.

Releated

C vs. Python: The Key Differences

Many millions of programmers rely on the Python and C programming languages. They may have functional similarities, but they also have core differences. Notably, the C programming language is quite a bit older. It came out in 1972, while Python first appeared in 1991. Since its arrival, programmers have positively embraced C for its speed […]

How to Encrypt a Password in Python Using bcrypt

Password encryption masks users’ passwords so they become hard to guess or decode. It’s an essential step in developing secure user-base software. Whether you’re building one with Flask or another light Python Framework, you can’t ignore that step. That’s where bcrypt comes in. We’ll show you how to use bcrypt to hash your password in […]