要重命名集合中的列名,可以使用$rename运算符。以下是语法
db.yourCollectionName.update({}, {$rename: {'yourOldColumName': 'yourNewColumnName'}}, false, true);
让我们首先创建一个包含文档的集合:
> db.renamingColumnNameDemo.insertOne({"StudentName":"Larry","Age":23}); { "acknowledged" : true, "insertedId" : ObjectId("5c9ee2c6d628fa4220163b9a") } > db.renamingColumnNameDemo.insertOne({"StudentName":"Sam","Age":26}); { "acknowledged" : true, "insertedId" : ObjectId("5c9ee2d0d628fa4220163b9b") } > db.renamingColumnNameDemo.insertOne({"StudentName":"Robert","Age":27}); { "acknowledged" : true, "insertedId" : ObjectId("5c9ee2dbd628fa4220163b9c") }
以下是在find()
方法的帮助下显示集合中所有文档的查询
> db.renamingColumnNameDemo.find().pretty();
这将产生以下输出
{ "_id" : ObjectId("5c9ee2c6d628fa4220163b9a"), "StudentName" : "Larry", "Age" : 23 } { "_id" : ObjectId("5c9ee2d0d628fa4220163b9b"), "StudentName" : "Sam", "Age" : 26 } { "_id" : ObjectId("5c9ee2dbd628fa4220163b9c"), "StudentName" : "Robert", "Age" : 27 }
以下是重命名MongoDB集合中列名称的查询
> db.renamingColumnNameDemo.update({}, {$rename: {'Age': 'StudentAge'}}, false, true); WriteResult({ "nMatched" : 3, "nUpserted" : 0, "nModified" : 3 })
现在检查“年龄”列是否已使用“ StudentAge”重命名
> db.renamingColumnNameDemo.find().pretty();
这将产生以下输出
{ "_id" : ObjectId("5c9ee2c6d628fa4220163b9a"), "StudentName" : "Larry", "StudentAge" : 23 } { "_id" : ObjectId("5c9ee2d0d628fa4220163b9b"), "StudentName" : "Sam", "StudentAge" : 26 } { "_id" : ObjectId("5c9ee2dbd628fa4220163b9c"), "StudentName" : "Robert", "StudentAge" : 27 }