w3resource
MongoDB Tutorial

MongoDB: db.collection.reIndex() method

db.collection.reIndex

The db.collection.reIndex() method is used to drop all indexes on a collection and recreates them.

Syntax:

db.collection.reIndex()

Call this method, which takes no arguments, on a collection object.

db.collection.reIndex()

Normally, MongoDB compacts indexes during routine updates. For most users, the db.collection.reIndex() is unnecessary. However, it may be worth running if the collection size has changed significantly or if the indexes are consuming a disproportionate amount of disk space.

Sample document in the restaurants collection:


{
  "address": {
     "building": "1007",
     "coord": [ -73.856077, 40.848447 ],
     "street": "Morris Park Ave",
     "zipcode": "10462"
  },
  "borough": "Bronx",
  "cuisine": "Bakery",
  "grades": [
     { "date": { "$date": 1393804800000 }, "grade": "A", "score": 2 },
     { "date": { "$date": 1378857600000 }, "grade": "A", "score": 6 },
     { "date": { "$date": 1358985600000 }, "grade": "A", "score": 10 },
     { "date": { "$date": 1322006400000 }, "grade": "A", "score": 9 },
     { "date": { "$date": 1299715200000 }, "grade": "B", "score": 14 }
  ],
  "name": "Morris Park Bake Shop",
  "restaurant_id": "30075445"
}
.....

Example: MongoDB: db.collection.reIndex() method

Following example drops all indexes on the collection restaurants and recreates them.

db.restaurants.reIndex();

Output:

> db.restaurants.reIndex();
{
        "nIndexesWas" : 1,
        "nIndexes" : 1,
        "indexes" : [
                {
                        "key" : {
                                "_id" : 1
                        },
                        "name" : "_id_",
                        "ns" : "test.restaurants"
                }
        ],
        "ok" : 1
}

Retrieve the restaurants data from here

NOTE: For replica sets, db.collection.reIndex() will not propagate from the primary to secondaries. db.collection.reIndex() will only affect a single mongod instance.

Previous: db.collection.mapReduce() method
Next: db.collection.remove() method



New Content: Composer: Dependency manager for PHP, R Programming