快速入门:将 Go 应用程序连接到 Azure Cosmos DB 的 API for MongoDBQuickstart: Connect a Go application to Azure Cosmos DB's API for MongoDB

适用于: Azure Cosmos DB API for MongoDB

Azure Cosmos DB 是一种多模型数据库服务,可让你通过多区域分布和水平缩放功能快速创建和查询文档、表、键/值和图数据库。Azure Cosmos DB is a multi-model database service that lets you quickly create and query document, table, key-value, and graph databases with multiple-region distribution and horizontal scale capabilities. 在本快速入门中,你将使用 Azure CLI 创建和管理 Azure Cosmos DB 帐户,从 GitHub 克隆现有示例应用程序并将其配置为使用 Azure Cosmos DB。In this quickstart, you create and manage an Azure Cosmos DB account by using the Azure CLI, clone an existing sample application from GitHub and configure it to work with Azure Cosmos DB.

示例应用程序是使用 Go 编写的基于命令行的 todo 管理工具。The sample application is a command-line based todo management tool written in Go. Azure Cosmos DB 的 API for MongoDB 与 MongoDB Wire Protocol 兼容,因而任何 MongoDB 客户端驱动程序都可以与其连接。Azure Cosmos DB's API for MongoDB is compatible with the MongoDB wire protocol, making it possible for any MongoDB client driver to connect to it. 此应用程序使用适用于 MongoDB 的 Go 驱动程序,其使用方式使该应用程序完全知道数据存储在 Azure Cosmos DB 数据库中。This application uses the Go driver for MongoDB in a way that is transparent to the application that the data is stored in an Azure Cosmos DB database.

先决条件Prerequisites

  • 具有活动订阅的 Azure 帐户。An Azure account with an active subscription. 免费创建一个Create one for free. 你还可以将 Azure Cosmos DB 模拟器与连接字符串 .mongodb://localhost:C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==@localhost:10255/admin?ssl=true 配合使用。You can also use the Azure Cosmos DB Emulator with the connection string .mongodb://localhost:C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==@localhost:10255/admin?ssl=true.

  • 在计算机上安装 Go,并了解 Go 的实践知识。Go installed on your computer, and a working knowledge of Go.

  • GitGit.

  • Azure CLI 2.0+Azure CLI 2.0+.

备注

在 Azure China 中使用 Azure CLI 2.0 之前,请首先运行 az cloud set -n AzureChinaCloud 更改云环境。Before you can use Azure CLI 2.0 in Azure China, please run az cloud set -n AzureChinaCloud first to change the cloud environment. 如果要切换回全局 Azure,请再次运行 az cloud set -n AzureCloudIf you want to switch back to Global Azure, run az cloud set -n AzureCloud again.

克隆示例应用程序Clone the sample application

运行以下命令克隆示例存储库。Run the following commands to clone the sample repository.

  1. 打开命令提示符,新建一个名为 git-samples 的文件夹,然后关闭命令提示符。Open a command prompt, create a new folder named git-samples, then close the command prompt.

    mkdir "C:\git-samples"
    
  2. 打开诸如 git bash 之类的 git 终端窗口,并使用 cd 命令更改为要安装示例应用的新文件夹。Open a git terminal window, such as git bash, and use the cd command to change to the new folder to install the sample app.

    cd "C:\git-samples"
    
  3. 运行下列命令以克隆示例存储库。Run the following command to clone the sample repository. 此命令在计算机上创建示例应用程序的副本。This command creates a copy of the sample app on your computer.

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

查看代码Review the code

此步骤是可选的。This step is optional. 如果有意了解应用程序的工作原理,可以查看以下代码片段。If you're interested in learning how the application works, you can review the following snippets. 否则,可以跳到运行应用程序Otherwise, you can skip ahead to Run the application. 应用程序布局如下所示:The application layout is as follows:

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

以下代码片段全部摘自 todo.go 文件。The following snippets are all taken from the todo.go file.

将 Go 应用连接到 Azure Cosmos DBConnecting the Go app to Azure Cosmos DB

clientOptions 封装 Azure Cosmos DB 的连接字符串,该字符串使用环境变量传入(后面一部分会详细介绍)。clientOptions encapsulates the connection string for Azure Cosmos DB, which is passed in using an environment variable (details in the upcoming section). 连接使用 mongo.NewClientclientOptions 实例传递的目标位置)进行初始化。The connection is initialized using mongo.NewClient to which the clientOptions instance is passed. 调用 Ping 函数以确认连接是否成功(这是一种快速失败策略)Ping function is invoked to confirm successful connectivity (it is a fail-fast strategy)

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

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

    c, err := mongo.NewClient(clientOptions)
    err = c.Connect(ctx)
    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 closedUsing the SetDirect(true) configuration is important, without which you will get the following connectivity error: unable to connect connection(cdb-ms-prod-<azure-region>-cm1.documents.azure.cn:10255[-4]) connection is closed

创建 todoCreate a todo item

若要创建 todo,我们将获取 mongo.Collection 的句柄,并调用 InsertOne 函数。To create a todo, we get a handle to a mongo.Collection and invoke the InsertOne function.

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 结构We pass in a Todo struct that contains the description and the status (which is initially set to pending)

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

列出 todoList todo items

我们可以根据条件列出 TODO。We can list TODOs based on criteria. 随之创建一个 bson.D 来封装筛选条件A bson.D is created to encapsulate the filter criteria

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 的切片Find is used to search for documents based on the filter and the result is converted into a slice of 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)
    }

最后,信息以表格格式呈现Finally, the information is rendered in tabular format

    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()

更新 todoUpdate a todo item

todo 可以基于其 _id 进行更新。A todo can be updated based on its _id. bson.D 筛选器根据 _id 创建,并且会为更新的信息创建另一个筛选器,该信息是这种情况下的新状态(completedpending)。A bson.D filter is created based on the _id and another one is created for the updated information, which is a new status (completed or pending) in this case. 最后,通过筛选器和更新后的文档调用 UpdateOne 函数Finally, the UpdateOne function is invoked with the filter and the updated document

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)
    }

删除 todoDelete a todo

todo 根据其 _id 进行删除,并以 bson.D 实例的形式封装。A todo is deleted based on its _id and it is encapsulated in the form of a bson.D instance. 调用 DeleteOne 以删除文档。DeleteOne is invoked to delete the document.

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)
    }
}

构建应用程序Build the application

转到在其中克隆应用程序的目录并生成应用程序(使用 go build)。Change into the directory where you cloned the application and build it (using go build).

cd monogdb-go-quickstart
go build -o todo

确认应用程序已正确生成。To confirm that the application was built properly.

./todo --help

安装 Azure Cosmos DBSetup Azure Cosmos DB

登录 AzureSign in to Azure

如果选择在本地安装并使用 CLI,本主题要求运行 Azure CLI 2.0 或更高版本。When you choose to install and use the CLI locally, this topic requires that you are running the Azure CLI version 2.0 or later. 运行 az --version 即可查找版本。Run az --version to find the version. 如果需要进行安装或升级,请参阅 [安装 Azure CLI]。If you need to install or upgrade, see [Install Azure CLI].

如果使用已安装的 Azure CLI,请使用 az login 命令登录到 Azure 订阅,按屏幕说明操作。If you are using an installed Azure CLI, sign in to your Azure subscription with the az login command and follow the on-screen directions.

az cloud set -n AzureChinaCloud
az login 

添加 Azure Cosmos DB 模块Add the Azure Cosmos DB module

如果使用已安装的 Azure CLI,请运行 az 命令,检查是否已安装 cosmosdb 组件。If you are using an installed Azure CLI, check to see if the cosmosdb component is already installed by running the az command. 如果 cosmosdb 在基本命令列表中,请继续执行下一个命令。If cosmosdb is in the list of base commands, proceed to the next command.

如果 cosmosdb 不在基本命令列表中,请重装 Azure CLIIf cosmosdb is not in the list of base commands, reinstall Azure CLI.

创建资源组Create a resource group

使用 az group create 创建资源组Create a resource group with the az group create. Azure 资源组是在其中部署和管理 Azure 资源(例如 Web 应用、数据库和存储帐户)的逻辑容器。An Azure resource group is a logical container into which Azure resources like web apps, databases and storage accounts are deployed and managed.

以下示例在中国北部区域中创建一个资源组。The following example creates a resource group in the China North region. 选择资源组的唯一名称。Choose a unique name for the resource group.

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

创建 Azure Cosmos DB 帐户Create an Azure Cosmos DB account

使用 az cosmosdb create 命令创建 Cosmos 帐户。Create a Cosmos account with the az cosmosdb create command.

在以下命令中,请将 <cosmosdb-name> 占位符替换成自己的唯一 Cosmos 帐户名。In the following command, please substitute your own unique Cosmos account name where you see the <cosmosdb-name> placeholder. 此唯一名称将用作 Cosmos DB 终结点 (https://<cosmosdb-name>.documents.azure.cn/) 的一部分,因此这个名称需要在 Azure 中的所有 Cosmos 帐户中具有唯一性。This unique name will be used as part of your Cosmos DB endpoint (https://<cosmosdb-name>.documents.azure.cn/), so the name needs to be unique across all Cosmos accounts in Azure.

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

--kind MongoDB 参数启用 MongoDB 客户端连接。The --kind MongoDB parameter enables MongoDB client connections.

创建 Azure Cosmos DB 帐户后,Azure CLI 会显示类似于以下示例的信息:When the Azure Cosmos DB account is created, the Azure CLI shows information similar to the following example.

备注

此示例使用 JSON 作为 Azure CLI 输出格式,此为默认设置。This example uses JSON as the Azure CLI output format, which is the default. 若要使用其他输出格式,请参阅 Azure CLI 命令的输出格式To use another output format, see Output formats for Azure CLI commands.

{
  "databaseAccountOfferType": "Standard",
  "documentEndpoint": "https://<cosmosdb-name>.documents.azure.cn:443/",
  "id": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myResourceGroup/providers/Microsoft.DocumentDB/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"
    }
  ]
} 

检索数据库键Retrieve the database key

若要连接到 Cosmos 数据库,需要使用数据库密钥。In order to connect to a Cosmos database, you need the database key. 使用 az cosmosdb keys list 命令检索主键。Use the az cosmosdb keys list command to retrieve the primary key.

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

Azure CLI 输出类似于以下示例的信息。The Azure CLI outputs information similar to the following example.

"RUayjYjixJDWG5xTqIiXjC..."

配置应用程序Configure the application

将连接字符串、MongoDB 数据库和集合名称导出为环境变量。Export the connection string, MongoDB database and collection names as environment variables.

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

备注

由于 Cosmos DB 的要求,ssl=true 选项很重要。The ssl=true option is important because of Cosmos DB requirements. 有关详细信息,请参阅连接字符串要求For more information, see Connection string requirements.

对于 MONGODB_CONNECTION_STRING 环境变量,请替换 <COSMOSDB_ACCOUNT_NAME><COSMOSDB_PASSWORD> 的占位符For the MONGODB_CONNECTION_STRING environment variable, replace the placeholders for <COSMOSDB_ACCOUNT_NAME> and <COSMOSDB_PASSWORD>

  1. <COSMOSDB_ACCOUNT_NAME>:创建的 Azure Cosmos DB 帐户的名称<COSMOSDB_ACCOUNT_NAME>: The name of the Azure Cosmos DB account you created
  2. <COSMOSDB_PASSWORD>:上一步中提取的数据库密钥<COSMOSDB_PASSWORD>: The database key extracted in the previous step
export MONGODB_DATABASE=todo-db
export MONGODB_COLLECTION=todos

可以为 MONGODB_DATABASEMONGODB_COLLECTION 选择首选值,也可以将其保留原样。You can choose your preferred values for MONGODB_DATABASE and MONGODB_COLLECTION or leave them as is.

运行应用程序Run the application

创建一个 todoTo create a todo

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

如果成功,则会看到一个输出,其中包含新建文档的 MongoDB _idIf successful, you should see an output with the MongoDB _id of the newly created document:

added todo ObjectID("5e9fd6befd2f076d1f03bd8a")

再创建一个 todoCreate another todo

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

列出所有 todoList all the todos

./todo --list all

应该会看到刚才以表格格式添加的那些文件You should see the ones you just added in a tabular format as such

+----------------------------+--------------------------------+-----------+
|             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 IDTo update the status of a todo (e.g. change it to completed status), use the todo ID

./todo --update 5e9fd6b1bcd2fa6bd267d4c4,completed

仅列出已完成的 todoList only the completed todos

./todo --list completed

应该会看到刚刚更新的那一项You should see the one you just updated

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

在数据资源管理器中查看数据View data in Data Explorer

Azure Cosmos DB 中存储的数据可用于在 Azure 门户中查看和查询。Data stored in Azure Cosmos DB is available to view and query in the Azure portal.

若要查看、查询和处理在上一步骤中创建的用户数据,请在 Web 浏览器中登录到 Azure 门户To view, query, and work with the user data created in the previous step, login to the Azure portal in your web browser.

在顶部搜索框中,输入 Azure Cosmos DBIn the top Search box, enter Azure Cosmos DB. 打开 Cosmos 帐户边栏选项卡后,请选择 Cosmos 帐户。When your Cosmos account blade opens, select your Cosmos account. 在左侧导航栏中,选择“数据资源管理器”。In the left navigation, select Data Explorer. 在“集合”窗格中展开你的集合,即可查看该集合中的文档,查询数据,甚至可以创建和运行存储过程、触发器与 UDF。Expand your collection in the Collections pane, and then you can view the documents in the collection, query the data, and even create and run stored procedures, triggers, and UDFs.

数据资源管理器,显示新创建的文档

使用 ID 删除 todoDelete a todo using it's ID

./todo --delete 5e9fd6b1bcd2fa6bd267d4c4,completed

列出要确认的 todoList the todos to confirm

./todo --list all

刚刚删除的 todo 不应出现The todo you just deleted should not be present

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

清理资源Clean up resources

执行完应用和 Azure Cosmos DB 帐户的操作以后,可以删除所创建的 Azure 资源,以免产生更多费用。When you're done with your app and Azure Cosmos DB account, you can delete the Azure resources you created so you don't incur more charges. 若要删除资源,请执行以下操作:To delete the resources:

  1. 在 Azure 门户的“搜索”栏中,搜索并选择“资源组” 。In the Azure portal Search bar, search for and select Resource groups.

  2. 从列表中选择为本快速入门创建的资源组。From the list, select the resource group you created for this quickstart.

    选择要删除的资源组

  3. 在资源组“概览”页上,选择“删除资源组” 。On the resource group Overview page, select Delete resource group.

    删除资源组

  4. 在下一窗口中输入要删除的资源组的名称,然后选择“删除” 。In the next window, enter the name of the resource group to delete, and then select Delete.

后续步骤Next steps

在本快速入门中,你已了解如何使用 Azure CLI 创建 Azure Cosmos DB MongoDB API 帐户,以及如何创建并运行 Go 命令行应用以管理 todoIn this quickstart, you learned how to create an Azure Cosmos DB MongoDB API account using the Azure CLI, and create and run a Go command-line app to manage todos. 现在可以将其他数据导入 Azure Cosmos DB 帐户了。You can now import additional data to your Azure Cosmos DB account.