How can I rename a collection in MongoDB?

后端 未结 5 720
醉梦人生
醉梦人生 2020-12-24 00:36

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

db.originalCollectionName.rename(\'newCollectionName\');

And if

相关标签:
5条回答
  • 2020-12-24 00:53

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

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

    0 讨论(0)
  • 2020-12-24 00:53

    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");
    
    0 讨论(0)
  • 2020-12-24 01:09

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

    0 讨论(0)
  • 2020-12-24 01:09

    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!

    0 讨论(0)
  • 2020-12-24 01:10

    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.

    0 讨论(0)
提交回复
热议问题