快速入门:将 Go 应用程序连接到 Azure Cosmos DB 的 API for MongoDB

适用对象: MongoDB

Azure Cosmos DB 是一种多模型数据库服务,可让你通过多区域分布和水平缩放功能快速创建和查询文档、表、键/值和图数据库。 在本快速入门中,你将使用 Azure CLI 创建和管理 Azure Cosmos DB 帐户,从 GitHub 克隆现有示例应用程序并将其配置为使用 Azure Cosmos DB。

示例应用程序是使用 Go 编写的基于命令行的 todo 管理工具。 Azure Cosmos DB 的 API for MongoDB 与 MongoDB Wire Protocol 兼容,因而任何 MongoDB 客户端驱动程序都可以与其连接。 此应用程序使用适用于 MongoDB 的 Go 驱动程序,其使用方式使该应用程序完全知道数据存储在 Azure Cosmos DB 数据库中。

先决条件

  • 具有活动订阅的 Azure 帐户。 创建一个。 或者免费试用 Azure Cosmos DB 而无需 Azure 订阅。 你还可以将 Azure Cosmos DB 模拟器与连接字符串 .mongodb://localhost:C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==@localhost:10255/admin?ssl=true 配合使用。
  • 在计算机上安装 Go,并了解 Go 的实践知识。
  • Git

可以使用本地 Azure CLI。

  • 如果需要,请安装 Azure CLI 来运行 CLI 参考命令。

  • 本地 Azure CLI,请了解如何安装 Azure CLI。 如果在 Windows 或 macOS 上运行,请考虑在 Docker 容器中运行 Azure CLI。 有关详细信息,请参阅如何在 Docker 容器中运行 Azure CLI

    • 通过使用 az login 命令登录到 Azure CLI。 若要完成身份验证过程,请遵循终端中显示的步骤。 有关其他登录选项,请参阅使用 Azure CLI 登录

    • 出现提示时,请在首次使用时安装 Azure CLI 扩展。 有关扩展详细信息,请参阅使用 Azure CLI 的扩展

    • 运行 az version 以查找安装的版本和依赖库。 若要升级到最新版本,请运行 az upgrade

克隆示例应用程序

运行以下命令克隆示例存储库。

  1. 打开命令提示符,新建一个名为 git-samples 的文件夹,然后关闭命令提示符。

    mkdir "C:\git-samples"
    
  2. 打开诸如 git bash 之类的 git 终端窗口,并使用 cd 命令更改为要安装示例应用的新文件夹。

    cd "C:\git-samples"
    
  3. 运行下列命令,克隆示例存储库。 此命令在计算机上创建示例应用程序的副本。

    git clone https://github.com/Azure-Samples/cosmosdb-go-mongodb-quickstart
    

查看代码

此步骤是可选的。 如果有意了解应用程序的工作原理,可以查看以下代码片段。 否则,可以跳到运行应用程序。 应用程序布局如下所示:

.
├── go.mod
├── go.sum
└── todo.go

以下代码片段全部摘自 todo.go 文件。

将 Go 应用连接到 Azure Cosmos DB

clientOptions 封装 Azure Cosmos DB 的连接字符串,该字符串使用环境变量传入(后面一部分会详细介绍)。 连接使用 mongo.NewClientclientOptions 实例传递的目标位置)进行初始化。 调用 Ping 函数以确认连接是否成功(这是一种快速失败策略)

    ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
    defer cancel()

    clientOptions := options.Client().ApplyURI(mongoDBConnectionString).SetDirect(true)

    c, err := mongo.Connect(ctx, clientOptions)
    if err != nil {
        log.Fatalf("unable to initialize connection %v", err)
    }

    err = c.Ping(ctx, nil)
    if err != nil {
        log.Fatalf("unable to connect %v", err)
    }

注意

务必使用 SetDirect(true) 配置,否则会出现以下连接错误:unable to connect connection(cdb-ms-prod-<azure-region>-cm1.documents.azure.cn:10255[-4]) connection is closed

创建 todo

若要创建 todo,我们将获取 mongo.Collection 的句柄,并调用 InsertOne 函数。

func create(desc string) {
    c := connect()
    ctx := context.Background()
    defer c.Disconnect(ctx)

    todoCollection := c.Database(database).Collection(collection)
    r, err := todoCollection.InsertOne(ctx, Todo{Description: desc, Status: statusPending})
    if err != nil {
        log.Fatalf("failed to add todo %v", err)
    }

传入包含说明和状态(最初设置为 pending)的 Todo 结构

type Todo struct {
    ID          primitive.ObjectID `bson:"_id,omitempty"`
    Description string             `bson:"description"`
    Status      string             `bson:"status"`
}

列出 todo

我们可以根据条件列出 TODO。 随之创建一个 bson.D 来封装筛选条件

func list(status string) {
    .....
    var filter interface{}
    switch status {
    case listAllCriteria:
        filter = bson.D{}
    case statusCompleted:
        filter = bson.D{{statusAttribute, statusCompleted}}
    case statusPending:
        filter = bson.D{{statusAttribute, statusPending}}
    default:
        log.Fatal("invalid criteria for listing todo(s)")
    }

Find 用于根据筛选器搜索文档,并将结果转换为 Todo 的切片

    todoCollection := c.Database(database).Collection(collection)
    rs, err := todoCollection.Find(ctx, filter)
    if err != nil {
        log.Fatalf("failed to list todo(s) %v", err)
    }
    var todos []Todo
    err = rs.All(ctx, &todos)
    if err != nil {
        log.Fatalf("failed to list todo(s) %v", err)
    }

最后,信息以表格格式呈现

    todoTable := [][]string{}

    for _, todo := range todos {
        s, _ := todo.ID.MarshalJSON()
        todoTable = append(todoTable, []string{string(s), todo.Description, todo.Status})
    }

    table := tablewriter.NewWriter(os.Stdout)
    table.SetHeader([]string{"ID", "Description", "Status"})

    for _, v := range todoTable {
        table.Append(v)
    }
    table.Render()

更新 todo

todo 可以基于其 _id 进行更新。 bson.D 筛选器根据 _id 创建,并且会为更新的信息创建另一个筛选器,该信息是这种情况下的新状态(completedpending)。 最后,通过筛选器和更新后的文档调用 UpdateOne 函数

func update(todoid, newStatus string) {
....
    todoCollection := c.Database(database).Collection(collection)
    oid, err := primitive.ObjectIDFromHex(todoid)
    if err != nil {
        log.Fatalf("failed to update todo %v", err)
    }
    filter := bson.D{{"_id", oid}}
    update := bson.D{{"$set", bson.D{{statusAttribute, newStatus}}}}
    _, err = todoCollection.UpdateOne(ctx, filter, update)
    if err != nil {
        log.Fatalf("failed to update todo %v", err)
    }

删除 todo

todo 根据其 _id 进行删除,并以 bson.D 实例的形式封装。 调用 DeleteOne 以删除文档。

func delete(todoid string) {
....
    todoCollection := c.Database(database).Collection(collection)
    oid, err := primitive.ObjectIDFromHex(todoid)
    if err != nil {
        log.Fatalf("invalid todo ID %v", err)
    }
    filter := bson.D{{"_id", oid}}
    _, err = todoCollection.DeleteOne(ctx, filter)
    if err != nil {
        log.Fatalf("failed to delete todo %v", err)
    }
}

构建应用程序

转到在其中克隆应用程序的目录并生成应用程序(使用 go build)。

cd monogdb-go-quickstart
go build -o todo

确认应用程序已正确生成。

./todo --help

安装 Azure Cosmos DB

登录 Azure

如果选择在本地安装并使用 CLI,本主题要求运行 Azure CLI 2.0 版或更高版本。 运行 az --version 即可查找版本。 如果需要进行安装或升级,请参阅 [安装 Azure CLI]。

如果使用已安装的 Azure CLI,请使用 az login 命令登录到 Azure 订阅,按屏幕说明操作。

az login 

添加 Azure Cosmos DB 模块

如果使用已安装的 Azure CLI,请运行 az 命令,检查是否已安装 cosmosdb 组件。 如果 cosmosdb 在基本命令列表中,请继续执行下一个命令。

如果 cosmosdb 不在基本命令列表中,请重装 Azure CLI

创建资源组

使用 az group create 创建资源组。 Azure 资源组是在其中部署和管理 Azure 资源(例如 Web 应用、数据库和存储帐户)的逻辑容器。

以下示例在中国北部区域中创建一个资源组。 选择资源组的唯一名称。

将以下命令复制到本地 CLI 命令提示符。

az group create --name myResourceGroup --location "China North"

创建 Azure Cosmos DB 帐户

使用 az cosmosdb create 命令创建 Azure Cosmos DB 帐户。

在以下命令中,请将 <cosmosdb-name> 占位符替换成自己的唯一 Azure Cosmos DB 帐户名。 此唯一名称将用作 Azure Cosmos DB 终结点 (https://<cosmosdb-name>.documents.azure.cn/) 的一部分,因此需要在 Azure 中的所有 Azure Cosmos DB 帐户之间保持唯一。

az cosmosdb create --name <cosmosdb-name> --resource-group myResourceGroup --kind MongoDB

--kind MongoDB 参数启用 MongoDB 客户端连接。

创建 Azure Cosmos DB 帐户后,Azure CLI 会显示类似于以下示例的信息:

注意

此示例使用 JSON 作为 Azure CLI 输出格式,此为默认设置。 若要使用其他输出格式,请参阅 Azure CLI 命令的输出格式

{
  "databaseAccountOfferType": "Standard",
  "documentEndpoint": "https://<cosmosdb-name>.documents.azure.cn:443/",
  "id": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myResourceGroup/providers/Microsoft.Document
DB/databaseAccounts/<cosmosdb-name>",
  "kind": "MongoDB",
  "location": "China North",
  "name": "<cosmosdb-name>",
  "readLocations": [
    {
      "documentEndpoint": "https://<cosmosdb-name>-chinanorth.documents.azure.cn:443/",
      "failoverPriority": 0,
      "id": "<cosmosdb-name>-chinanorth",
      "locationName": "China North",
      "provisioningState": "Succeeded"
    }
  ],
  "resourceGroup": "myResourceGroup",
  "type": "Microsoft.DocumentDB/databaseAccounts",
  "writeLocations": [
    {
      "documentEndpoint": "https://<cosmosdb-name>-chinanorth.documents.azure.cn:443/",
      "failoverPriority": 0,
      "id": "<cosmosdb-name>-chinanorth",
      "locationName": "China North",
      "provisioningState": "Succeeded"
    }
  ]
} 

检索数据库键

若要连接到 Azure Cosmos DB 数据库,需要使用数据库密钥。 使用 az cosmosdb keys list 命令检索主键。

az cosmosdb keys list --name <cosmosdb-name> --resource-group myResourceGroup --query "primaryMasterKey"

Azure CLI 输出类似于以下示例的信息。

"RUayjYjixJDWG5xTqIiXjC..."

配置应用程序

将连接字符串、MongoDB 数据库和集合名称导出为环境变量。

export MONGODB_CONNECTION_STRING="mongodb://<COSMOSDB_ACCOUNT_NAME>:<COSMOSDB_PASSWORD>@<COSMOSDB_ACCOUNT_NAME>.documents.azure.cn:10255/?ssl=true&replicaSet=globaldb&maxIdleTimeMS=120000&appName=@<COSMOSDB_ACCOUNT_NAME>@"

注意

由于 Azure Cosmos DB 的要求,ssl=true 选项很重要。 有关详细信息,请参阅连接字符串要求

对于 MONGODB_CONNECTION_STRING 环境变量,请替换 <COSMOSDB_ACCOUNT_NAME><COSMOSDB_PASSWORD> 的占位符

  1. <COSMOSDB_ACCOUNT_NAME>:创建的 Azure Cosmos DB 帐户的名称
  2. <COSMOSDB_PASSWORD>:上一步中提取的数据库密钥
export MONGODB_DATABASE=todo-db
export MONGODB_COLLECTION=todos

可以为 MONGODB_DATABASEMONGODB_COLLECTION 选择首选值,也可以将其保留原样。

运行应用程序

创建一个 todo

./todo --create "Create an Azure Cosmos DB database account"

如果成功,则会看到一个输出,其中包含新建文档的 MongoDB _id

added todo ObjectID("5e9fd6befd2f076d1f03bd8a")

再创建一个 todo

./todo --create "Get the MongoDB connection string using the Azure CLI"

列出所有 todo

./todo --list all

应该会看到刚才以表格格式添加的那些文件

+----------------------------+--------------------------------+-----------+
|             ID             |          DESCRIPTION           |  STATUS   |
+----------------------------+--------------------------------+-----------+
| "5e9fd6b1bcd2fa6bd267d4c4" | Create an Azure Cosmos DB      | pending   |
|                            | database account               |           |
| "5e9fd6befd2f076d1f03bd8a" | Get the MongoDB connection     | pending   |
|                            | string using the Azure CLI     |           |
+----------------------------+--------------------------------+-----------+

若要更新 todo 的状态(例如将其更改为 completed 状态),请使用 todo ID

./todo --update 5e9fd6b1bcd2fa6bd267d4c4,completed

仅列出已完成的 todo

./todo --list completed

应该会看到刚刚更新的那一项

+----------------------------+--------------------------------+-----------+
|             ID             |          DESCRIPTION           |  STATUS   |
+----------------------------+--------------------------------+-----------+
| "5e9fd6b1bcd2fa6bd267d4c4" | Create an Azure Cosmos DB      | completed |
|                            | database account               |           |
+----------------------------+--------------------------------+-----------+

在数据资源管理器中查看数据

Azure Cosmos DB 中存储的数据可用于在 Azure 门户中查看和查询。

若要查看、查询和处理在上一步骤中创建的用户数据,请在 Web 浏览器中登录到 Azure 门户

在顶部搜索框中,输入 Azure Cosmos DB。 打开 Azure Cosmos DB 帐户边栏选项卡后,请选择你的 Azure Cosmos DB 帐户。 在左侧导航栏中,选择“数据资源管理器”。 在“集合”窗格中展开你的集合,即可查看该集合中的文档,查询数据,甚至可以创建和运行存储过程、触发器与 UDF。

Data Explorer showing the newly created document

使用 ID 删除 todo

./todo --delete 5e9fd6b1bcd2fa6bd267d4c4,completed

列出要确认的 todo

./todo --list all

刚刚删除的 todo 不应出现

+----------------------------+--------------------------------+-----------+
|             ID             |          DESCRIPTION           |  STATUS   |
+----------------------------+--------------------------------+-----------+
| "5e9fd6befd2f076d1f03bd8a" | Get the MongoDB connection     | pending   |
|                            | string using the Azure CLI     |           |
+----------------------------+--------------------------------+-----------+

清理资源

执行完应用和 Azure Cosmos DB 帐户的操作以后,可以删除所创建的 Azure 资源,以免产生更多费用。 若要删除资源,请执行以下操作:

  1. 在 Azure 门户的“搜索”栏中,搜索并选择“资源组” 。

  2. 从列表中选择为本快速入门创建的资源组。

    Select the resource group to delete

  3. 在资源组“概览”页上,选择“删除资源组” 。

    Delete the resource group

  4. 在下一窗口中输入要删除的资源组的名称,然后选择“删除” 。

后续步骤

在本快速入门中,你已了解如何使用 Azure CLI 创建 Azure Cosmos DB for MongoDB 帐户,以及如何创建并运行 Go 命令行应用以管理 todo。 现在可以将其他数据导入 Azure Cosmos DB 帐户了。

尝试为迁移到 Azure Cosmos DB 进行容量规划? 可以使用有关现有数据库群集的信息进行容量规划。