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
Does MongoDB track how many times each index is used in a query?
Yes, MongoDB tracks index usage statistics through the $indexStats aggregation stage. This allows you to monitor how frequently each index is accessed, helping optimize database performance by identifying unused or heavily used indexes.
Syntax
db.collection.aggregate([
{ $indexStats: {} }
]);
Create Sample Data
First, let's create an index on the FirstName field ?
db.demo508.createIndex({"FirstName": 1});
{
"createdCollectionAutomatically": true,
"numIndexesBefore": 1,
"numIndexesAfter": 2,
"ok": 1
}
Now insert sample documents ?
db.demo508.insertMany([
{"FirstName": "John"},
{"FirstName": "Chris"},
{"FirstName": "David"}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e883818987b6e0e9d18f578"),
ObjectId("5e88381b987b6e0e9d18f579"),
ObjectId("5e88381f987b6e0e9d18f57a")
]
}
View Collection Data
db.demo508.find();
{ "_id": ObjectId("5e883818987b6e0e9d18f578"), "FirstName": "John" }
{ "_id": ObjectId("5e88381b987b6e0e9d18f579"), "FirstName": "Chris" }
{ "_id": ObjectId("5e88381f987b6e0e9d18f57a"), "FirstName": "David" }
Track Index Usage Statistics
Use $indexStats to see how many times each index has been accessed ?
db.demo508.aggregate([
{ $indexStats: {} }
]);
{
"name": "_id_",
"key": {
"_id": 1
},
"host": "DESKTOP-QN2RB3H:27017",
"accesses": {
"ops": NumberLong(0),
"since": ISODate("2020-04-04T07:32:27.394Z")
}
}
{
"name": "FirstName_1",
"key": {
"FirstName": 1
},
"host": "DESKTOP-QN2RB3H:27017",
"accesses": {
"ops": NumberLong(0),
"since": ISODate("2020-04-04T07:32:27.527Z")
}
}
Key Points
- ops: Number of operations that used this index
- since: Timestamp when tracking started (server restart or index creation)
- name: Index name (auto-generated or custom)
- Statistics reset when the server restarts or index is rebuilt
Conclusion
The $indexStats aggregation stage provides valuable insights into index usage patterns. Monitor these statistics regularly to identify unused indexes for removal and heavily used indexes that may need optimization.
Advertisements
