如何在 MongoDB 中重命名集合?

mongodbdatabasebig data analytics更新于 2026/1/21 20:07:17

要在 MongoDB 中重命名集合,可以使用 renameCollection() 方法。语法如下:−

db.yourOldCollectionName.renameCollection('yourNewCollectionName');

为了理解上述语法,让我们列出数据库 sample 中的所有集合。查询如下:−

> use sample;
switched to db sample
> show collections;

以下是输出 −

copyThisCollectionToSampleDatabaseDemo
deleteDocuments
deleteDocumentsDemo
employee
informationAboutDelete
internalArraySizeDemo
prettyDemo
selectWhereInDemo
sourceCollection
updateInformation
userInformation

现在将集合名称"informationAboutDelete"更改为"deleteSomeInformation"。更改集合名称的查询如下。

> db.informationAboutDelete.renameCollection("deleteSomeInformation");
{ "ok" : 1 }

以下查询用于检查集合名称是否已重命名为"deleteSomeInformation" −

> show collections;

以下是输出 −

copyThisCollectionToSampleDatabaseDemo
deleteDocuments
deleteDocumentsDemo
deleteSomeInformation
employee
internalArraySizeDemo
prettyDemo
selectWhereInDemo
sourceCollection
updateInformation
userInformation

相关文章