mongo之$rename更新一個欄位的名稱(可批量)
阿新 • • 發佈:2018-11-22
$rename
操作邏輯執行$unset
老名稱和新的名稱,然後執行 $set
新名稱執行。因此,操作可能不保留文件中欄位的順序; 即重新命名的欄位可以在文件內移動。
1、重新命名欄位:一級欄位
格式:
db.students.updateMany( {}, { $rename: { "nmae": "name" } } )
eg:
#原集合 { "_id": 1, "alias": [ "The American Cincinnatus", "The American Fabius" ], "mobile": "555-555-5555", "nmae": { "first" : "george", "last" : "washington" } } { "_id": 2, "alias": [ "My dearest friend" ], "mobile": "222-222-2222", "nmae": { "first" : "abigail", "last" : "adams" } } { "_id": 3, "alias": [ "Amazing grace" ], "mobile": "111-111-1111", "nmae": { "first" : "grace", "last" : "hopper" } } #修改:批量把所有的nmae 欄位改成name,也可以在第一個花括號裡面指定修改哪一個id記錄的nmae db.students.updateMany( {}, { $rename: { "nmae": "name" } } ) #輸出: { "_id": 1, "alias": [ "The American Cincinnatus", "The American Fabius" ], "mobile": "555-555-5555", "name": { "first" : "george", "last" : "washington" } } { "_id" : 2, "alias" : [ "My dearest friend" ], "mobile" : "222-222-2222", "name" : { "first" : "abigail", "last" : "adams" } } { "_id" : 3, "alias" : [ "Amazing grace" ], "mobile" : "111-111-1111", "name" : { "first" : "grace", "last" : "hopper" } }
2、重新命名嵌入文件中的欄位
eg:
#元集合: { "_id": 1, "alias": [ "The American Cincinnatus", "The American Fabius" ], "mobile": "555-555-5555", "name": { "first" : "george", "last" : "washington" } } { "_id" : 2, "alias" : [ "My dearest friend" ], "mobile" : "222-222-2222", "name" : { "first" : "abigail", "last" : "adams" } } { "_id" : 3, "alias" : [ "Amazing grace" ], "mobile" : "111-111-1111", "name" : { "first" : "grace", "last" : "hopper" } } #修改 db.students.update( { _id: 1 }, { $rename: { "name.first": "name.fname" } } ) #結果 { "_id" : 1, "alias" : [ "The American Cincinnatus", "The American Fabius" ], "mobile" : "555-555-5555", "name" : { "fname" : "george", "last" : "washington" } }
註釋:
×重新命名不存在的欄位
重新命名欄位並且現有欄位名稱引用不存在的欄位時,$rename操作員不執行任何操作