MySQL 9.0 版本注意事項
若要使用綱要中的集合,請使用 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。