快速入門導覽課程:建立並連線至資料庫

瞭解如何建立與 MongoDB 相容的 Firestore 資料庫,並使用 mongosh 工具連線至該資料庫。

事前準備

  1. In the Google Cloud console, go to the project selector page.

    Go to project selector

  2. Select or create a Google Cloud project.

  3. Verify that billing is enabled for your Google Cloud project.

  4. Make sure that you have the following role or roles on the project: Cloud Datastore Owner

    Check for the roles

    1. In the Google Cloud console, go to the IAM page.

      Go to IAM
    2. Select the project.
    3. In the Principal column, find all rows that identify you or a group that you're included in. To learn which groups you're included in, contact your administrator.

    4. For all rows that specify or include you, check the Role column to see whether the list of roles includes the required roles.

    Grant the roles

    1. In the Google Cloud console, go to the IAM page.

      前往「身分與存取權管理」頁面
    2. 選取專案。
    3. 按一下 「授予存取權」
    4. 在「New principals」(新增主體) 欄位中,輸入您的使用者 ID。 這通常是 Google 帳戶的電子郵件地址。

    5. 在「Select a role」(選取角色) 清單中,選取角色。
    6. 如要授予其他角色,請按一下 「新增其他角色」,然後新增每個其他角色。
    7. 按一下 [Save]
  5. 安裝 mongosh 工具
  6. 建立與 MongoDB 相容的 Firestore 資料庫,並擷取連線字串

    在 Google Cloud 控制台中,建立新的 Firestore Enterprise 版資料庫。與 MongoDB 相容的 Firestore 需要 Firestore Enterprise 版:

    1. 前往 Google Cloud 控制台的「Databases」頁面。

      前往「資料庫」

    2. 點選「建立 Firestore 資料庫」
    3. 輸入資料庫 ID。
    4. 選取 Enterprise 版本。
    5. 選取資料庫位置。
    6. 按一下 [Create Database] (建立資料庫)。

      資料庫完成初始化後,控制台會開啟資料庫的 Firestore Studio

    7. 在「使用外部 MongoDB 工具連結至 Firestore」部分,複製連線字串。

    連線字串取決於資料庫的 UID (系統產生) 和資料庫位置:

    UID.LOCATION.firestore.goog

    建立 SCRAM 驗證的使用者

    在 Google Cloud 控制台中,建立新的資料庫使用者,並指派使用者身分與存取權管理權限。

    1. 前往 Google Cloud 控制台的「Databases」頁面。

      前往「資料庫」

    2. 從資料庫清單中選取資料庫。
    3. 按一下導覽選單中的「Auth」(驗證)
    4. 點選「Add User」
    5. 輸入使用者名稱。
    6. 為使用者選取 Identity and Access Management 角色。
    7. 按一下「建立」。資料庫會建立使用者,並顯示該使用者產生的密碼。複製並儲存這組密碼。您將無法在日後擷取這組密碼。

    使用 mongosh 連線

    使用連線字串、使用者名稱和密碼連線至資料庫,並在本機執行 mongosh,設定選項如下。

    mongosh 'mongodb://USERNAME:PASSWORD@CONNECTION_STRING:443/DATABASE_ID?loadBalanced=true&authMechanism=SCRAM-SHA-256&tls=true&retryWrites=false'

    更改下列內容:

    • USERNAME:您建立的資料庫使用者名稱。
    • PASSWORD:為您建立的資料庫使用者產生的密碼。
    • CONNECTION_STRING:資料庫連線字串。
    • DATABASE_ID:資料庫 ID

    連線後,您就可以建立及讀取資料,例如:

    db.pages.insertOne({ message: "Hello World!"})
    db.pages.find({})
    exit

    後續步驟