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
Rebuilding indexes in MongoDB?
To rebuild indexes in MongoDB, use the reIndex() method. This operation rebuilds all indexes on a collection, which can help resolve index corruption or optimize index performance after significant data changes.
Syntax
db.collection.reIndex()
Create Sample Index
Let us first create an index to demonstrate the rebuilding process ?
db.demo42.createIndex({"StudentFirstName": 1})
{
"createdCollectionAutomatically" : true,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}
Rebuild All Indexes
Following is the query to rebuild all indexes in the collection ?
db.demo42.reIndex()
{
"nIndexesWas" : 2,
"nIndexes" : 2,
"indexes" : [
{
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "web.demo42"
},
{
"v" : 2,
"key" : {
"StudentFirstName" : 1
},
"name" : "StudentFirstName_1",
"ns" : "web.demo42"
}
],
"ok" : 1
}
Key Points
-
reIndex()rebuilds all indexes on the collection, including the default_idindex. - This operation blocks all read and write operations on the collection during execution.
- Use sparingly, as it can be resource-intensive on large collections.
Conclusion
The reIndex() method rebuilds all indexes in a collection, helping resolve corruption issues and optimize performance. Use it cautiously as it blocks collection access during execution.
Advertisements
