Aaron Silverman
Aaron Silverman

Reputation: 22655

How can I rename a collection in MongoDB?

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?

Upvotes: 75

Views: 70227

Answers (7)

XML
XML

Reputation: 19508

The MongoDB Compass desktop app now makes this even 'dead easy'-er:

  1. Click on the ... menu that appears to the right of the collection name on hover
  2. Select Rename Collection
  3. Enter new name
  4. Confirm (and accept potential consequences)

enter image description here

Upvotes: 0

Uku Lele
Uku Lele

Reputation: 604

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

Upvotes: 3

arispen
arispen

Reputation: 3000

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");

Upvotes: 7

Arun Kumar N
Arun Kumar N

Reputation: 1669

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!

Upvotes: 0

Lakshmikandan
Lakshmikandan

Reputation: 4647

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.

Upvotes: 18

Ev0oD
Ev0oD

Reputation: 1871

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")

Upvotes: 20

nav
nav

Reputation: 3125

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

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

Upvotes: 129

Related Questions