How can I rename a collection in MongoDB?

MongodbCollectionsRename

Mongodb Problem Overview


Is there a dead easy way to rename a collection in mongo? Something like:

db.originalCollectionName.rename('newCollectionName');

And if not, what is the best way to go about effectively renaming one?

Mongodb Solutions


Solution 1 - Mongodb

Close. Use db.originalCollectionName.renameCollection('newCollectionName')

See http://www.mongodb.org/display/DOCS/renameCollection+Command

Solution 2 - Mongodb

Assume that the database name is "mytestdb" and collection name is "orders". collection name change to orders2015 The simplest way is,

> use mytestdb
> db.orders.renameCollection( "orders2015" )

Note : db.collection.renameCollection() is not supported on sharded collections.

Solution 3 - Mongodb

For those who cannot rename, because the name causes an issue like: SyntaxError: Unexpected token ILLEGAL, it is because the name is illegal.

You can work around this by calling with brackets notation: db["oldCollectionILLEGALName"].renameCollection("someBetterName")

Solution 4 - Mongodb

In case you are using Node.js MongoDB driver:

mongoClient.db(dbName).collection('oldName').rename("newName");

https://mongodb.github.io/node-mongodb-native/3.5/api/Collection.html#rename

my case was using mongoose:

await mongoose.connection.collection("oldName").rename("newName");

Solution 5 - Mongodb

Rename a collection in cmd:

cd C:\Program Files\MongoDB\Server\4.2\bin
mongo
use yourdb
db.yourcollection.renameCollection("someBetterName")

This example is made for MongoDB 4.2

Solution 6 - Mongodb

You can use the following syntax to rename an existing collection in MongoDB.

db.originalCollectionName.renameCollection('newCollectionName')

For instance, if your existing collection name is 'demo' and want to rename to 'demo_updated' then, the query would be as follows:-

db.demo.renameCollection('demo_updated')

Thanks!

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAaron SilvermanView Question on Stackoverflow
Solution 1 - MongodbnavView Answer on Stackoverflow
Solution 2 - MongodbLakshmikandanView Answer on Stackoverflow
Solution 3 - MongodbEv0oDView Answer on Stackoverflow
Solution 4 - MongodbarispenView Answer on Stackoverflow
Solution 5 - MongodbUku LeleView Answer on Stackoverflow
Solution 6 - MongodbArun Kumar NView Answer on Stackoverflow