文件首頁
MySQL 9.0 參考手冊
相關文件 下載本手冊
PDF (美式信紙) - 40.0Mb
PDF (A4) - 40.1Mb
Man Pages (TGZ) - 258.2Kb
Man Pages (Zip) - 365.3Kb
Info (Gzip) - 4.0Mb
Info (Zip) - 4.0Mb


22.3.3.2 使用集合

若要使用綱要中的集合,請使用 db 全域物件存取目前的綱要。在此範例中,我們使用的是先前匯入的 world_x 綱要和 countryinfo 集合。因此,您發出的作業格式為 db.collection_name.operation,其中 collection_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

相關資訊