![]() |
VOOZH | about |
Single-field indexes in MongoDB improve query performance by indexing one specific field, allowing faster lookups and sorting on that field.
MongoDB allows specifying additional options when creating indexes to customize their behavior. Some common options include:
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
}
)
To create a single field index in MongoDB, you can use the createIndex() method.
db.books.createIndex({ title: 1 })Output:
title_1This output confirms that the index was successfully created and added to the collection.
Create an index to sort and retrieve books by their publication year in descending order.
db.books.createIndex({ publishedYear: -1 })Output:
publishedYear_-1Modify 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:
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:
author.firstName_1 Create an index to efficiently search for books based on the entire author object in the books collection.
db.books.createIndex({ author: 1 })Output:
author_1Single-field indexes offer several benefits, as defined below:
While single field indexes provide significant performance benefits, it's essential to consider the following factors: