您可以使用 modify()
方法來更新集合中的一個或多個文件。X DevAPI 提供額外的方法與 modify()
方法搭配使用,以執行下列操作:
設定和取消設定文件中的欄位。
附加、插入和刪除陣列。
繫結、限制和排序要修改的文件。
modify()
方法的工作方式是篩選集合,使其僅包含要修改的文件,然後將您指定的作業套用至這些文件。
在下列範例中,modify()
方法使用搜尋條件來識別要變更的文件,然後 set()
方法會取代巢狀 demographics 物件中的兩個值。
mysql-js> db.countryinfo.modify("Code = 'SEA'").set(
"demographics", {"LifeExpectancy": 78, "Population": 28})
修改文件後,請使用 find()
方法來驗證變更。
若要從文件中移除內容,請使用 modify()
和 unset()
方法。例如,下列查詢會從符合搜尋條件的文件中移除 GNP。
mysql-js> db.countryinfo.modify("Name = 'Sealand'").unset("GNP")
使用 find()
方法來驗證變更。
mysql-js> db.countryinfo.find("Name = 'Sealand'")
{
"_id": "00005e2ff4af00000000000000f4",
"Name": "Sealand",
"Code:": "SEA",
"IndepYear": 1967,
"geography": {
"Region": "British Islands",
"Continent": "Europe",
"SurfaceArea": 193
},
"government": {
"HeadOfState": "Michael Bates",
"GovernmentForm": "Monarchy"
},
"demographics": {
"Population": 27,
"LifeExpectancy": 79
}
}
若要將元素附加至陣列欄位,或插入或刪除陣列中的元素,請使用 arrayAppend()
、arrayInsert()
或 arrayDelete()
方法。下列範例會修改 countryinfo
集合,以啟用國際機場追蹤。
第一個範例會使用 modify()
和 set()
方法,在所有文件中建立新的 Airports 欄位。
當您修改文件而不指定搜尋條件時,請謹慎使用;這樣做會修改集合中的所有文件。
mysql-js> db.countryinfo.modify("true").set("Airports", [])
加入 Airports 欄位後,下一個範例會使用 arrayAppend()
方法,將新的機場新增至其中一個文件。下列範例中的 $.Airports 代表目前文件的 Airports 欄位。
mysql-js> db.countryinfo.modify("Name = 'France'").arrayAppend("$.Airports", "ORY")
使用 find()
來查看變更。
mysql-js> db.countryinfo.find("Name = 'France'")
{
"GNP": 1424285,
"_id": "00005de917d80000000000000048",
"Code": "FRA",
"Name": "France",
"Airports": [
"ORY"
],
"IndepYear": 843,
"geography": {
"Region": "Western Europe",
"Continent": "Europe",
"SurfaceArea": 551500
},
"government": {
"HeadOfState": "Jacques Chirac",
"GovernmentForm": "Republic"
},
"demographics": {
"Population": 59225700,
"LifeExpectancy": 78.80000305175781
}
}
若要將元素插入陣列中的不同位置,請使用 arrayInsert()
方法來指定要在路徑表達式中插入的索引。在此案例中,索引為 0,也就是陣列中的第一個元素。
mysql-js> db.countryinfo.modify("Name = 'France'").arrayInsert("$.Airports[0]", "CDG")
若要從陣列中刪除元素,您必須將要刪除之元素的索引傳遞至 arrayDelete()
方法。
mysql-js> db.countryinfo.modify("Name = 'France'").arrayDelete("$.Airports[1]")
MySQL 參考手冊提供說明,協助您搜尋和修改 JSON 值。
如需完整的語法定義,請參閱 CollectionModifyFunction。