$rename
可用于对文档字段的重命名。
使用方式:
{$rename: { <field1>: <newName1>, <field2>: <newName2>, ... } }
使用实例:
students集合的文档:
{
"_id": 1,
"alias": [ "The American Cincinnatus", "The American Fabius" ],
"mobile": "555-555-5555",
"name": { "first" : "george", "last" : "washington" },
"friend": [
{"first" : "zhang", "last" : "san"},
{"first" : "li", "last" : "si"}
]
}
{
"_id": 2,
"alias": [ "My dearest friend" ],
"mobile": "222-222-2222",
"name": { "first" : "abigail", "last" : "adams" },
"friend": [
{"first" : "zhang", "last" : "san"},
{"first" : "li", "last" : "si"}
]
}
{
"_id": 3,
"alias": [ "Amazing grace" ],
"mobile": "111-111-1111",
"name": { "first" : "grace", "last" : "hopper" },
"friend": [
{"first" : "zhang", "last" : "san"},
{"first" : "li", "last" : "si"}
]
}
对students集合所有文档的nam字段更改为name,name.first字段更改为name.firstName,如下
db.getCollection('students').updateMany({},{$rename:{
"nam":"name",
"name.first":"name.firstName"
}});
注!!!
$rename对于数组内对象的key值暂无法更改
例如:friend数组内的first字段无法通过$rename变更。
变更数组内对象的key值
但数组内对象的key值可以通过遍历进行修改
例如下面的语句:
db.getCollection('students').find({}).forEach( function(item){
for(let i = 0; i<item["friend"].length; i++){
item["friend"][i].firstName = item["friend"][i].first;
delete item["friend"][i].first;
}
db.getCollection('students').update({"_id":item["_id]}, item);
}
)
这样就可以将friend数组内的first字段变更为firstName字段。
!!!!!!