MySQL 8.4 版本注意事項
若要處理綱要中的集合,請使用 db
全域物件來存取目前的綱要。在此範例中,我們使用先前匯入的 world_x
綱要和 countryinfo
集合。因此,您發出的作業格式為 db.
,其中 collection_name
.operationcollection_name
是執行作業的集合名稱。在以下範例中,作業是針對 countryinfo
集合執行的。
使用 add()
方法將一個文件或文件清單插入現有集合中。將以下文件插入 countryinfo
集合中。由於這是多行內容,請按 Enter 兩次以插入文件。
mysql-py> db.countryinfo.add(
{
"GNP": .6,
"IndepYear": 1967,
"Name": "Sealand",
"Code:": "SEA",
"demographics": {
"LifeExpectancy": 79,
"Population": 27
},
"geography": {
"Continent": "Europe",
"Region": "British Islands",
"SurfaceArea": 193
},
"government": {
"GovernmentForm": "Monarchy",
"HeadOfState": "Michael Bates"
}
}
)
該方法會傳回作業的狀態。您可以藉由搜尋文件來驗證作業。例如
mysql-py> db.countryinfo.find("Name = 'Sealand'")
{
"GNP": 0.6,
"_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
}
}
請注意,除了新增文件時指定的欄位外,還有一個欄位 _id
。每個文件都需要一個名為 _id
的識別碼欄位。_id
欄位的值在同一個集合中的所有文件中必須是唯一的。文件 ID 是由伺服器 (而非用戶端) 產生的,因此 MySQL Shell 不會自動設定 _id
值。如果文件不包含 _id
欄位,MySQL 會設定 _id
值。如需更多資訊,請參閱瞭解文件 ID。
請參閱CollectionAddFunction 以取得完整的語法定義。
請參閱瞭解文件 ID。