Search code examples
mongodbmongodb-queryrenaming

How does mongo rename collection works?


I am confused by how mongo renames collections and how much time will it take to rename a very large collection.

Here is the scenario, I have a mongo collection with too much data (588 million documents), which slows down finding and insertion, so I creating an archive collection to keep all this data. For this I am thinking to rename the old collection to oldcollectionname_archive and start with a fresh collection with oldcollectionname. And planning to do this by following command :

db.oldCollectionName.renameCollection("oldCollectionName_archive")

But I am not sure, how much time it will take. I read the mongodocs and many stackoverflow answers regarding collection renaming, but I could find anywhere any data regarding whether the size of the collection affect the time required to renaming the collection.

Please help if anyone has any knowledge regarding this or any same experience.

Note : I have read other issues which can occur during renaming, on mongo documentation and other SO answers.


Solution

  • From the mongodb documentation (https://docs.mongodb.com/manual/reference/command/renameCollection/)

    renameCollection has different performance implications depending on the target namespace.

    If the target database is the same as the source database, renameCollection simply changes the namespace. This is a quick operation.

    If the target database differs from the source database, renameCollection copies all documents from the source collection to the target collection. Depending on the size of the collection, this may take longer to complete. Other operations which require exclusive access to the affected databases will be blocked until the rename completes. See What locks are taken by some common client operations? for operations which require exclusive access to all databases.

    Note that: * renameCollection is not compatible with sharded collections. * renameCollection fails if target is the name of an existing collection and you do not specify dropTarget: true.