快速入门:创建数据库并连接到该数据库
了解如何创建具有 MongoDB 兼容性的 Firestore 数据库,以及如何使用 mongosh
工具连接到该数据库。
准备工作
-
In the Google Cloud console, go to the project selector page.
-
Select or create a Google Cloud project.
-
Make sure that billing is enabled for your Google Cloud project.
-
Make sure that you have the following role or roles on the project: roles/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 - 选择项目。
- 点击 授予访问权限。
-
在新的主账号字段中,输入您的用户标识符。 这通常是 Google 账号的电子邮件地址。
- 在选择角色列表中,选择一个角色。
- 如需授予其他角色,请点击 添加其他角色,然后添加其他各个角色。
- 点击 Save(保存)。
-
- 安装
mongosh
工具
创建具有 MongoDB 兼容性的 Firestore 数据库并检索连接字符串
在 Google Cloud 控制台中,创建一个新的 Firestore 企业版数据库。 具有 MongoDB 兼容性的 Firestore 需要 Firestore 企业版:
-
在 Google Cloud 控制台中,转到数据库页面。
- 点击创建 Firestore 数据库。
- 输入数据库 ID。
- 选择“企业版”。
- 为数据库选择位置。
点击创建数据库。
数据库完成初始化后,控制台会为您的数据库打开 Firestore Studio。
-
在使用外部 MongoDB 工具连接到 Firestore 部分,复制连接字符串。
连接字符串取决于数据库的 UID(系统生成)和数据库的位置:
UID.LOCATION.firestore.goog
创建用于 SCRAM 身份验证的用户
在 Google Cloud 控制台中,创建一个新的数据库用户并为该用户分配 Identity and Access Management 权限。
-
在 Google Cloud 控制台中,转到数据库页面。
- 从数据库列表中选择数据库。
- 在导航菜单中,点击身份验证。
- 点击 Add User(添加用户)。
- 输入用户名。
- 为用户选择一个 Identity and Access Management 角色。
- 点击“创建”。数据库会创建用户,并向您显示用户生成的密码。复制并保存此密码。您日后将无法检索此密码。
使用 mongosh
连接
使用连接字符串、用户名和密码连接到数据库,并使用以下配置选项在本地运行 mongosh
。
mongosh 'mongodb://USERNAME:PASSWORD@CONNECTION_STRING:443/DATABASE_ID?loadBalanced=true&authMechanism=SCRAM-SHA-256&authMechanismProperties=ENVIRONMENT:gcp,TOKEN_RESOURCE:FIRESTORE&tls=true&retryWrites=false'
替换以下内容:
- USERNAME:您创建的数据库用户的名称。
- PASSWORD:为您创建的数据库用户生成的密码。
- CONNECTION_STRING:数据库连接字符串。
- DATABASE_ID:数据库 ID
连接后,您可以创建和读取数据,例如:
db.pages.insertOne({ message: "Hello World!"}) db.pages.find({}) exit
清理
如需清理此页面上使用的资源,请删除数据库用户并删除数据库。
删除数据库用户
删除数据库用户,以移除该用户以及分配给该用户的 Identity and Access Management 权限。
-
在 Google Cloud 控制台中,转到数据库页面。
- 从数据库列表中选择数据库。
- 在导航菜单中,点击身份验证。
- 在要删除的用户对应的操作列中,点击 操作。点击删除用户。 系统随即会显示一个对话框。
- 确认删除并点击删除。
- 系统会显示一个指向 IAM 页面的链接。点击相应链接,即可删除分配给数据库用户的权限。
-
找到包含要撤消其访问权限的主账号的行。然后,点击该行中的
修改主账号。您创建的数据库用户的主账号使用以下命名格式:
principal://firestore.googleapis.com/projects/PROJECT_NUMBER/name/databases/DATABASE_ID/userCreds/USER_ID
- 点击要撤消的角色对应的删除 按钮,然后点击保存。
删除数据库
如需删除数据库,请完成以下操作:
-
在 Google Cloud 控制台中,转到数据库页面。
- 在要删除的数据库对应的操作列中,点击 查看更多。点击删除。随即会出现一个对话框。
在要删除数据库吗?对话框中,通过在文本字段中输入相应数据库 ID 来确认删除。点击删除。控制台会通知您操作成功还是失败。