如何重命名 MongoDB 中的集合?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8732553/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I rename a collection in MongoDB?
提问by Zugwalt
Is there a dead easy way to rename a collection in mongo? Something like:
有没有一种简单的方法可以在 mongo 中重命名集合?就像是:
db.originalCollectionName.rename('newCollectionName');
And if not, what is the best way to go about effectively renaming one?
如果不是,那么有效地重命名一个的最佳方法是什么?
回答by nav
Close. Use db.originalCollectionName.renameCollection('newCollectionName')
关闭。用db.originalCollectionName.renameCollection('newCollectionName')
See http://www.mongodb.org/display/DOCS/renameCollection+Command
见http://www.mongodb.org/display/DOCS/renameCollection+Command
回答by Ev0oD
For those who cannot rename, because the name causes an issue like: SyntaxError: Unexpected token ILLEGAL, it is because the name is illegal.
对于那些无法重命名的人,因为名称会导致类似的问题:SyntaxError: Unexpected token ILLEGAL,这是因为名称是非法的。
You can work around this by calling with brackets notation: db["oldCollectionILLEGALName"].renameCollection("someBetterName")
您可以通过使用括号表示法调用来解决此问题: db["oldCollectionILLEGALName"].renameCollection("someBetterName")
回答by lakshmikandan
Assume that the database name is "mytestdb" and collection name is "orders". collection name change to orders2015The simplest way is,
假设数据库名称是“ mytestdb”,集合名称是“ orders”。集合名称更改为orders2015最简单的方法是,
> use mytestdb
> db.orders.renameCollection( "orders2015" )
Note :db.collection.renameCollection() is not supported on sharded collections.
注意:分片集合不支持 db.collection.renameCollection()。
回答by Arun Kumar N
You can use the following syntax to rename an existing collection in MongoDB.
您可以使用以下语法重命名 MongoDB 中的现有集合。
db.originalCollectionName.renameCollection('newCollectionName')
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:-
例如,如果您现有的集合名称是“demo”并且想要重命名为“demo_updated”,那么查询将如下所示:-
db.demo.renameCollection('demo_updated')
Thanks!
谢谢!
回答by arispen
In case you are using Node.js MongoDB driver:
如果您使用的是 Node.js MongoDB 驱动程序:
mongoClient.db(dbName).collection('oldName').rename("newName");
https://mongodb.github.io/node-mongodb-native/3.5/api/Collection.html#rename
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");