在 MongoDB 集合中重新命名列名?
要重新命名集合中的列名称,可以使用 $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 })
现在,检查列 Age 是否已用“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 }
广告