MongoDB Creating Indexes
Creating Indexes (Single Field, Compound)
Single Field Indexes In MongoDB
In MongoDB, indexes play a crucial role in improving query performance by efficiently locating and retrieving documents from collections. One type of index commonly used is the single-field index, which indexes a single field within a collection.
In this article, we will learn about the concept of single field indexes in MongoDB by explaining their importance and usage by providing practical examples with outputs.
Single Field Indexes In MongoDB
An index in MongoDB is a data structure that improves the speed of data retrieval operations by providing an efficient way to locate documents within a collection. Single-field indexes are indexes created on a single field of a document. They enable faster queries based on the values of that specific field.
Types of Indexes
MongoDB supports various types of indexes, including
- Single Field Index: It Indexes a single field in a collection.
- Compound Index: It Indexes multiple fields together as a compound key.
- Multikey Index: It Indexes the elements of an array field.
- Text Index: It Supports text search operations on string content.
- Geospatial Index: It Indexes geographic data for efficient location-based queries.
- Hashed Index: It Hashes the indexed field value to support hash-based equality queries.
Let's set up an Environment:
To understand Single Field Indexes In MongoDB we need a collection and some documents on which we will perform various operations and queries. Here we will consider a collection called books which contains information in various documents are shown below.
([
{
"title": "MongoDB Basics",
"author": "John Doe",
"publishedYear": 2021
},
{
"title": "Advanced MongoDB Techniques",
"author": "Jane Smith",
"publishedYear": 2020
},
{
"title": "Mastering MongoDB",
"author": "Alice Johnson",
"publishedYear": 2019
}
]);
Examples of Single Field Indexes
A single field index in MongoDB is created on a specific field within a collection. This type of index is effective for queries that filter, sort or match documents based on a particular field's value.
Example 1: Create an Index on a Single Field
To create a single field index in MongoDB, we youcan use the createIndex() method. Let's consider an example where we have a collection named books with documents representing books, and we want to create an index on the title field:
Query:
db.books.createIndex({ title: 1 })
Output:
[
{ v: 2, key: { _id: 1 }, name: '_id_' },
{ v: 2, key: { title: 1 }, name: 'title_1' }
]
Explanation: This output confirms that the index was successfully created and added to the collection.
Example 2: Create an Ascending Index on a Single Field
Let's create an index to sort and retrieve books by their publication year efficiently.
Query:
db.books.createIndex({ publishedYear: 1 })
Output:
{
"createdCollectionAutomatically": false,
"numIndexesBefore": 1,
"numIndexesAfter": 2,
"ok": 1
}
Example 3: Create an Index on an Embedded Field
Let's modify the documents to include embedded fields:
[
{
"title": "MongoDB Basics",
"author": { "firstName": "John", "lastName": "Doe" },
"publishedYear": 2021
},
{
"title": "Advanced MongoDB Techniques",
"author": { "firstName": "Jane", "lastName": "Smith" },
"publishedYear": 2020
},
{
"title": "Mastering MongoDB",
"author": { "firstName": "Alice", "lastName": "Johnson" },
"publishedYear": 2019
}
]
Query:
Let's create an index to quickly search for books by the author's first name in the books
collection.
db.books.createIndex({ "author.firstName": 1 })
Output:
{
"createdCollectionAutomatically": false,
"numIndexesBefore": 2,
"numIndexesAfter": 3,
"ok": 1
}
Example 4: Create an Index on an Embedded Document
Let's create an index to efficiently search for books based on the entire author object in the books
collection.
Query:
db.books.createIndex({ author: 1 })
Output:
{
"createdCollectionAutomatically": false,
"numIndexesBefore": 3,
"numIndexesAfter": 4,
"ok": 1
}
Index Properties
MongoDB allows specifying additional options when creating indexes to customize their behavior. Some common options include:
- Unique Index: Ensures that indexed field values are unique across the collection.
- Sparse Index: Indexes only documents that contain the indexed field, ignoring documents that do not have the field.
- Partial Index: Indexes documents based on a specified filter expression.
Benefits of Single Field Indexes
Single field indexes offer several benefits are defined below:
- Improved Query Performance: Single field indexes speed up query execution by providing faster access to documents based on the indexed field.
- Reduced Disk I/O: By facilitating quicker data retrieval, single field indexes help reduce disk I/O operations, resulting in overall improved database performance.
- Optimized Sorting Operations: Indexes can also optimize sorting operations, enabling faster sorting of query results based on the indexed field.
- Enhanced Data Access Efficiency: With indexes, MongoDB can efficiently locate and access specific documents, leading to improved data access efficiency.
Considerations
While single field indexes provide significant performance benefits, it's essential to consider the following factors:
- Index Maintenance Overhead: Indexes consume storage space and require maintenance overhead during write operations. Consider the impact on write performance when creating indexes.
- Index Selectivity: Ensure that the indexed field has sufficient selectivity to warrant the creation of an index. Fields with low selectivity may not benefit significantly from indexing.
- Query Patterns: Analyze query patterns to identify fields that are frequently queried and would benefit from indexing. Focus on indexing fields that are commonly used in query predicates, sorting, or aggregation stages.
Conclusion
Overall, Single field indexes are a fundamental aspect of MongoDB's indexing mechanism by providing significant performance benefits for query operations. By efficiently organizing and accessing data based on the values of a single field and these indexes optimize query execution and enhance overall database performance. Understanding the concepts and benefits of single field indexes allow MongoDB developers to make informed decisions regarding index creation and query optimization strategies.
MongoDB Compound Indexes
MongoDB Compound Indexes is an index on multiple fields in a MongoDB collection. It can be created to enhance the performance of queries that need to filter on multiple fields. A MongoDB compound index can cover queries that request only the indexed fields, improving efficiency by avoiding reading the actual documents.
Compound Indexes do indexing on multiple fields of the document either in ascending or descending order i.e. it will sort the data of one field and then inside that it will sort the data of another field. In other words, compound indexes are those indexes where a single index field contains references to multiple fields.
Create a Compound Index
In MongoDB, we can create a compound index using the createIndex() method.
Syntax:
db.collection.createIndex({<field1>: <type1>, <field2>: <type2>, ...})
Here <type> represents the value of the field in the index specification and describes the kind of index for that field. For example, a value 1 for indexing in ascending order or value -1 for indexing in descending order.
For example:
{"id":"1", "product":"chips", "manufacturer":"lays", "price":20}
{"id":"2", "product":"pringles", "manufacturer":"Kellogg's", "price":99}
{"id":"3", "product":"Doritos", "manufacturer":"lays", "price":10}
{"id":"4", "product":"cheetos", "manufacturer":"lays", "price":473}
{"id":"5", "product":"coldrink", "manufacturer":"mountain-dew", "price":20}
In the above four documents, we can index them on both the field's name and age in any order. Suppose we create a compound index by db.collection.createIndex(manufacturer:1, price:-1) than index will look somewhat like this

As shown in the picture firstly Kellogs, Lays and mountain-dew are sorted alphabetically, and then the prices are sorted inside them. Here the indexing will be firstly done in ascending order of the manufacturer name and after that indexing will be done in descending order on price. So we can run queries like db.collection.find().sort(manufacturer:1, price: -1) efficiently as we have created an index for that.
Examples of Compound Indexes
In the following examples, we are working with:
- Database: GeeksforGeeks
- Collection: products
- Documents: Six documents that contain the details of the employees in the form of field-value pairs.
Example 1: Creating a compound index on manufacture and price
Here we are creating an index on manufacture in ascending order and then on price in descending order.
db.products.createIndex({manufacturer:1, price:-1})
Output:
Example 2: Creating a compound index on product, manufacturer, and price
Here we are creating an index on the product in ascending order then it will be sorted for the manufacturer in ascending order, and then it will again be sorted for price
Query:
db.products.createIndex({product:1,manufacturer:1,price:1})
Output:
Sorting using Compound Indexes
- We can use the sort() function for sorting the data into particular Sort Order on the created index as indexes contain ordered records.
- MongoDB can obtain the results of a sort from an index with which are Sort expression matches(matching using prefix).
- If MongoDB cannot use an index to obtain the sort order it performs a blocking sort operation on the data in which it consumes and processes all input documents to the sort before returning results.
- If the sort keys match an index prefix, MongoDB can use the index to sort the query results. A prefix is a subset that consists of one or more keys of the index key pattern.
For e.g. suppose we create a compound index by
db.data.createIndex({a:1, b: -1, c:1})
Then we have the following prefixes on which our created index is used for sorting -
{a:1}
{a:1,b:-1}
{a:1,b-1,c:1}
Example | prefix |
---|---|
db.data.find().sort({a: 1}) | {a: 1} |
db.data.find().sort({a: -1}) | {a: 1} |
db.data.find().sort({a: 1, b: -1}) | {a: 1, b: -1} |
db.data.find().sort({a: -1, b: 1}) | {a: 1, b: -1} |
db.data.find().sort({a: 1, b: -1, c: 1}) | {a: 1, b: -1, c: 1} |
So for all the examples in the above table MongoDB will use our created index but not on db.data.find().sort({a: -1, b: -1}) or db.data.find().sort({a: 1, b: 1}) as they don't match any prefix for these two MongoDB has to perform blocking sort.
We can also use non-prefix like {b: -1, c: 1} for sorting but for this, we have to put equality on the preceding prefix key .for e.g.
db.data.find({a: 6}).sort({b: -1, c: 1})
Here we have put an equality condition on key 'a' and now it will use prefix {a: 1, b: -1, c: 1}
Example:
db.products.find().sort({manufacturer:1,price:-1})
Output:
In the above example since our sort key pattern has manufacture:1, price:-1 which is similar to the second index manufacture_1_price_-1 key thus this index will be used to obtain result instead of doing sort again.
Conclusion
MongoDB compound indexes are a robust mechanism for enhancing the performance of queries that involve multiple fields. By creating these indexes, we can significantly improve the performance and efficiency of your database operations. Understanding how to create and use compound indexes effectively is essential for maximizing the potential of your MongoDB collections.
Created By :- Abhishek Pawar
Sri Balaji University
TYBCA(D)
Excellent work
ReplyDeleteVery nice
ReplyDeleteBrilliant work 👍🏻 keep it up !
ReplyDeleteGood job bro 🙌🏻
ReplyDeleteGood job bro...👍
ReplyDeleteThat's Brilliant 👍 Good Work Abhi
ReplyDeleteNice 👏🏼
ReplyDeleteExcellent 👌
ReplyDeleteExcellent work👍🏻
ReplyDeleteNice 👌
ReplyDelete