Index are created on the fields to get better performance while data retrieval , index can be created in two ways,
- Ascending order (1)
- Descending order (-1)
Syntax: db.collection.createIndex(‘field’:’option’)
Example:
Creating the index for ‘studentDetails’ collection for ‘Name’ field in ascending order
db.studentDetails.createIndex({Name:1})
Creating the index for ‘studentDetails’ collection for ‘Department’ field in descending order
db.studentDetails.createIndex({Department:-1})