MySQL 8.4 發行說明
若要使用綱要中的集合,請使用 db
全域物件來存取目前的綱要。在此範例中,我們使用先前匯入的 world_x
綱要和 countryinfo
集合。因此,您發出的操作格式為 db.
,其中 collection_name
.operationcollection_name
是執行操作的集合名稱。在下列範例中,操作是針對 countryinfo
集合執行的。
使用 add()
方法將一個文件或文件清單插入現有的集合。將下列文件插入 countryinfo
集合。由於這是多行內容,請按兩次 Enter 以插入文件。
mysql-js> 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-js> 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。