0% completed
Single field indexes in MongoDB are the simplest type of index and are used to index a single field within a document. They can significantly enhance the performance of read operations by allowing MongoDB to quickly locate documents that match a query condition on that indexed field. Single field indexes are particularly useful for queries that filter or sort on a single field.
db.collection.createIndex({ <field>: <type> }, { <option1>: <value1>, <option2>: <value2>, ... })
Let's insert some documents into the employees
collection:
db.employees.insertMany([ { name: "John Doe", age: 29, department: "HR" }, { name: "Jane Smith", age: 34, department: "Finance" }, { name: "Emily Davis", age: 42, department: "IT" }, { name: "Michael Brown", age: 36, department: "Marketing" }, { name: "Sarah Wilson", age: 30, department: "Sales" } ])
Create an index on the name
field:
db.employees.createIndex({ name: 1 }, { unique: true, name: "uniqueNameIndex" })
Explanation:
db.employees.createIndex({ name: 1 }, { unique: true, name: "uniqueNameIndex" })
: Creates a unique index on the name
field in ascending order. This index ensures that each name in the employees
collection is unique.Example 1: Query by Indexed Field
db.employees.find({ name: "Jane Smith" })
Explanation:
name
field to quickly locate the document where name
is "Jane Smith".Example 2: Sort by Indexed Field
db.employees.find().sort({ name: 1 })
Explanation:
name
field to efficiently sort the documents by name in ascending order.Single field indexes in MongoDB are essential tools for optimizing query performance, supporting efficient sorting, and enforcing uniqueness. By understanding the syntax, benefits, and considerations, you can effectively use single field indexes to improve the efficiency and performance of your MongoDB queries.
.....
.....
.....