快速入門導覽課程:建立並連線至資料庫
瞭解如何建立與 MongoDB 相容的 Firestore 資料庫,並使用 mongosh
工具連線至該資料庫。
事前準備
-
In the Google Cloud console, go to the project selector page.
-
Select or create a Google Cloud project.
Roles required to select or create a project
- Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
-
Create a project: To create a project, you need the Project Creator
(
roles/resourcemanager.projectCreator
), which contains theresourcemanager.projects.create
permission. Learn how to grant roles.
-
Verify that billing is enabled for your Google Cloud project.
-
Make sure that you have the following role or roles on the project: Cloud Datastore Owner
Check for the roles
-
In the Google Cloud console, go to the IAM page.
Go to IAM - Select the project.
-
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.
- 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
-
In the Google Cloud console, go to the IAM page.
前往「IAM」(身分與存取權管理) 頁面 - 選取專案。
- 按一下 「授予存取權」。
-
在「New principals」(新增主體) 欄位中,輸入您的使用者 ID。 這通常是 Google 帳戶的電子郵件地址。
- 在「Select a role」(選取角色) 清單中,選取角色。
- 如要授予其他角色,請按一下 「新增其他角色」,然後新增每個其他角色。
- 按一下 [Save]。
- 安裝
mongosh
工具建立與 MongoDB 相容的 Firestore 資料庫,並擷取連線字串
在 Google Cloud 控制台中,建立新的 Firestore Enterprise 版資料庫。與 MongoDB 相容的 Firestore 需要 Firestore Enterprise 版:-
前往 Google Cloud 控制台的「Databases」頁面。
- 點選「建立 Firestore 資料庫」。
- 輸入資料庫 ID。
- 選取 Enterprise 版本。
- 選取資料庫位置。
按一下 [Create Database] (建立資料庫)。
資料庫完成初始化後,控制台會開啟資料庫的 Firestore Studio。
-
在「使用外部 MongoDB 工具連結至 Firestore」部分,複製連線字串。
連線字串取決於資料庫的 UID (系統產生) 和資料庫位置:
UID.LOCATION.firestore.goog
建立 SCRAM 驗證的使用者
在 Google Cloud 控制台中,建立新的資料庫使用者,並指派使用者身分與存取權管理權限。
-
前往 Google Cloud 控制台的「Databases」頁面。
- 從資料庫清單中選取資料庫。
- 按一下導覽選單中的「Auth」(驗證)。
- 點選「Add User」。
- 輸入使用者名稱。
- 為使用者選取 Identity and Access Management 角色。
- 按一下「建立」。資料庫會建立使用者,並顯示該使用者產生的密碼。複製並儲存這組密碼。您將無法在日後擷取這組密碼。。
使用
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
後續步驟
-