For AI agents: a documentation index is available at https://www.mongodb.com/docs/llms.txt — markdown versions of all pages are available by appending .md to any URL path.
Docs Menu

Create an Index on a Single Field

You can create an index on a single field to improve performance for queries on that field.

To create a single-field index, use the db.collection.createIndex() method:

db.<collection>.createIndex( { <field>: <sort-order> } )

Create a students collection that contains the following documents:

db.students.insertMany( [
{
"name": "Alice",
"gpa": 3.6,
"location": { city: "Sacramento", state: "California" }
},
{
"name": "Bob",
"gpa": 3.2,
"location": { city: "Albany", state: "New York" }
}
] )

The following examples show you how to:

Consider a school administrator who frequently looks up students by their GPA. You can create an index on the gpa field to improve performance for those queries:

db.students.createIndex( { gpa: 1 } )

The index supports queries that select on the field gpa, such as the following:

db.students.find( { gpa: 3.6 } )
db.students.find( { gpa: { $lt: 3.4 } } )

You can create indexes on fields within embedded documents. Indexes on embedded fields can fulfill queries that use dot notation.

The location field is an embedded document that contains the embedded fields city and state. Create an index on the location.state field:

db.students.createIndex( { "location.state": 1 } )

The index supports queries on the field location.state, such as the following:

db.students.find( { "location.state": "California" } )
db.students.find( { "location.city": "Albany", "location.state": "New York" } )