Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How do I display the indexes of a collection in MongoDB?
To display the indexes of a collection in MongoDB, use the getIndexes() method. This method returns information about all indexes defined on the specified collection, including the default _id index.
Syntax
db.collectionName.getIndexes();
Sample Data
Let's create a collection with sample documents ?
db.indexDemo.insertMany([
{ "StudentName": "Larry", "StudentAge": 21 },
{ "StudentName": "Mike", "StudentAge": 24 },
{ "StudentName": "Carol", "StudentAge": 20 }
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5c8f7c4f2f684a30fbdfd599"),
ObjectId("5c8f7c552f684a30fbdfd59a"),
ObjectId("5c8f7c5e2f684a30fbdfd59b")
]
}
Example 1: Default Indexes
Display indexes before creating any custom ones ?
db.indexDemo.getIndexes();
[
{
"v": 2,
"key": {
"_id": 1
},
"name": "_id_",
"ns": "test.indexDemo"
}
]
Example 2: After Creating Custom Indexes
Create a compound index and display all indexes ?
db.indexDemo.createIndex({ "StudentName": -1, "StudentAge": -1 });
{
"createdCollectionAutomatically": false,
"numIndexesBefore": 1,
"numIndexesAfter": 2,
"ok": 1
}
Now display all indexes ?
db.indexDemo.getIndexes();
[
{
"v": 2,
"key": {
"_id": 1
},
"name": "_id_",
"ns": "test.indexDemo"
},
{
"v": 2,
"key": {
"StudentName": -1,
"StudentAge": -1
},
"name": "StudentName_-1_StudentAge_-1",
"ns": "test.indexDemo"
}
]
Key Points
- Every collection has a default
_idindex that cannot be dropped. - The
keyfield shows the indexed fields and their sort order (1 = ascending, -1 = descending). - The
namefield displays the auto-generated index name based on the field names and sort order.
Conclusion
The getIndexes() method provides a complete view of all indexes on a collection, helping you understand query optimization and index management strategies.
Advertisements
