Search code examples
mongodbindexingreindex

Does mongodb reindex if you change the field that it is used in index?


Lets say you have a collection with a field called "primary_key", {"primary_key":"1234", "name":"jimmy", "lastname":"page"}

and I have an index on "primary_key".

This collection has millions of rows, I want to see how expensive is to change primary_key for one of the records. Does it trigger a reindex of the entire table? or does it just reindex the changed record? in either case is that expensive to do?


Solution

  • Updating an indexed field in mongodb causes an update of the index (or indices if you have more than one) that use it. It does not "reindex". Shouldn't be all that expensive - effectively you will delete the old entry and insert a new one.

    This document has a fair amount of detail on mongodb indexes:

    http://docs.mongodb.org/master/MongoDB-indexes-guide.pdf

    BTW, keep in mind that there is one special field, _id, that mongodb uses as it's primary key

    _id A field required in every MongoDB document. The _id field must have a unique value. You can think of the _id field as the document’s primary key. If you create a new document without an _id field, MongoDB automatically creates the field and assigns a unique BSON ObjectId.

    You cannot update the _id field.