快速入门:创建数据库并与其连接
了解如何创建与 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 - 选择项目。
- 点击 授予访问权限。
-
在新的主账号字段中,输入您的用户标识符。 这通常是 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 控制台中,前往数据库页面。
- 从数据库列表中选择数据库。
- 在导航菜单中,点击 Auth。
- 点击添加用户。
- 输入用户名。
- 为用户选择 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
后续步骤
-