快速入门:创建数据库并与其连接

了解如何创建与 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.

      前往 IAM
    2. 选择项目。
    3. 点击 授予访问权限
    4. 新的主账号字段中,输入您的用户标识符。 这通常是 Google 账号的电子邮件地址。

    5. 选择角色列表中,选择一个角色。
    6. 如需授予其他角色,请点击 添加其他角色,然后添加其他各个角色。
    7. 点击 Save(保存)。
  5. 安装 mongosh 工具
  6. 创建与 MongoDB 兼容的 Firestore 数据库并检索连接字符串

    在 Google Cloud 控制台中,创建新的 Firestore 企业版数据库。 与 MongoDB 兼容的 Firestore 需要使用 Firestore 企业版:

    1. 在 Google Cloud 控制台中,前往数据库页面。

      前往“数据库”

    2. 点击创建 Firestore 数据库
    3. 输入数据库 ID。
    4. 选择企业版。
    5. 选择数据库的位置。
    6. 点击创建数据库

      数据库完成初始化后,控制台会为您的数据库打开 Firestore Studio

    7. 使用外部 MongoDB 工具连接到 Firestore 部分中,复制连接字符串。

    连接字符串取决于数据库的 UID(系统生成的)和数据库的位置:

    UID.LOCATION.firestore.goog

    为 SCRAM 身份验证创建用户

    在 Google Cloud 控制台中,创建新的数据库用户并为该用户分配 Identity and Access Management 权限。

    1. 在 Google Cloud 控制台中,前往数据库页面。

      前往“数据库”

    2. 从数据库列表中选择数据库。
    3. 在导航菜单中,点击 Auth
    4. 点击添加用户
    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

    后续步骤