快速入門:使用 Azure Cosmos DB 適用於 MongoDB 的 API 和 Golang SDK 建置主控台應用程式Quickstart: Build a console app using Azure Cosmos DB's API for MongoDB and Golang SDK

Azure Cosmos DB 是 Microsoft 的全域分散式多模型資料庫服務。Azure Cosmos DB is Microsoft’s globally distributed multi-model database service. 您可以快速建立及查詢文件、索引鍵/值及圖形資料庫,所有這些都受惠於位於 Cosmos DB 核心的全域散發和水平調整功能。You can quickly create and query document, key/value, and graph databases, all of which benefit from the global distribution and horizontal scale capabilities at the core of Cosmos DB.

本快速入門示範如何採用以 Golang 撰寫的現有 MongoDB 應用程式,並使用 Azure Cosmos DB 適用於 MongoDB 的 API 將它連線到 Cosmos 資料庫。This quickstart demonstrates how to take an existing MongoDB app written in Golang and connect it to your Cosmos database using the Azure Cosmos DB's API for MongoDB.

換句話說,您的 Golang 應用程式只知道它使用 MongoDB 用戶端進行連線。In other words, your Golang application only knows that it's connecting using a MongoDB client. 對於資料儲存在 Cosmos 資料庫中的應用程式而言是透明的。It is transparent to the application that the data is stored in a Cosmos database.

必要條件Prerequisites

  • Azure 訂用帳戶。An Azure subscription. 如果您沒有 Azure 訂用帳戶,請在開始前建立免費帳戶If you don’t have an Azure subscription, create a free account before you begin.

    或者,您可以免費試用 Azure Cosmos DB,無須 Azure 訂用帳戶,也無須任何費用和約定付款。Alternatively, you can Try Azure Cosmos DB for free without an Azure subscription, free of charge and commitments. 或者,您可以使用 Azure Cosmos DB 模擬器來進行本教學課程,連接字串為Or you can use the Azure Cosmos DB Emulator for this tutorial with a connection string of

    mongodb://localhost:C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==@localhost:10255/admin?ssl=true
    
  • Go 語言的 Go 和基本知識。Go and a basic knowledge of the Go language.

  • IDE — Jetbrains 的 GoLand、Microsoft 的 Visual Studio 程式碼AtomAn IDE — GoLand by Jetbrains, Visual Studio Code by Microsoft, or Atom. 在本教學課程中,我是使用 GoLand。In this tutorial, I'm using GoLand.

建立資料庫帳戶Create a database account

  1. 在新的視窗中,登入 Azure 入口網站In a new window, sign in to the Azure portal.

  2. 在左側功能表中,依序選取 [建立資源] 、[資料庫] ,然後在 [Azure Cosmos DB] 下選取 [建立] 。In the left menu, select Create a resource, select Databases, and then under Azure Cosmos DB, select Create.

    Azure 入口網站的螢幕擷取畫面,其中反白顯示 [其他服務] 和 Azure Cosmos DB

  3. 在 [建立 Azure Cosmos DB 帳戶] 頁面中,輸入新的 Azure Cosmos DB 帳戶的設定。In the Create Azure Cosmos DB Account page, enter the settings for the new Azure Cosmos DB account.

    設定Setting Value 說明Description
    SubscriptionSubscription 您的訂用帳戶Your subscription 選取要用於此 Azure Cosmos DB 帳戶的 Azure 訂用帳戶。Select the Azure subscription that you want to use for this Azure Cosmos DB account.
    資源群組Resource Group 新建Create new

    然後輸入識別碼中所提供的同一個唯一名稱Then enter the same unique name as provided in ID
    選取 [建立新的] 。Select Create new. 然後為您的帳戶輸入新的資源群組名稱。Then enter a new resource-group name for your account. 為求簡化,請使用和識別碼相同的名稱。For simplicity, use the same name as your ID.
    帳戶名稱Account Name 輸入唯一名稱Enter a unique name 輸入唯一名稱來識別您的 Azure Cosmos DB 帳戶。Enter a unique name to identify your Azure Cosmos DB account. 因為 documents.azure.com 會附加到您所提供的識別碼以建立 URI,請使用唯一識別碼。Because documents.azure.com is appended to the ID that you provide to create your URI, use a unique ID.

    識別碼只能使用小寫字母、數字及連字號 (-) 字元。The ID can use only lowercase letters, numbers, and the hyphen (-) character. 長度必須介於 3 到 31 個字元之間。It must be between 3 and 31 characters in length.
    APIAPI 適用於 MongoDB 的 Azure Cosmos DB APIAzure Cosmos DB's API for MongoDB API 會決定要建立的帳戶類型。The API determines the type of account to create. Azure Cosmos DB 提供五個 API:Core (SQL) (適用於文件資料庫)、Gremlin (適用於圖形資料庫)、Azure Cosmos DB MongoDB API (適用於文件資料庫)、「Azure 資料表」及 Cassandra。Azure Cosmos DB provides five APIs: Core (SQL) for document databases, Gremlin for graph databases, Azure Cosmos DB's API MongoDB for document databases, Azure Table, and Cassandra. 目前,您必須為每個 API 建立個別個帳戶。Currently, you must create a separate account for each API.

    選取 [MongoDB] ,因為在此快速入門中,您會建立可搭配 MongoDB 使用的資料表。Select MongoDB because in this quickstart you are creating a table that works with the MongoDB.
    LocationLocation 選取最接近使用者的區域Select the region closest to your users 選取用來裝載 Azure Cosmos DB 帳戶的地理位置。Select a geographic location to host your Azure Cosmos DB account. 使用最接近使用者的位置,以便他們能以最快速度存取資料。Use the location that's closest to your users to give them the fastest access to the data.

    請選取 [檢閱 + 建立] 。Select Review+Create. 您可以略過 [網路] 和 [標記] 區段。You can skip the Network and Tags section.

    Azure Cosmos DB 的新帳戶頁面

  4. 建立帳戶需要幾分鐘的時間。The account creation takes a few minutes. 等候入口網站顯示 [恭喜!具有 MongoDB 有線通訊協定相容性的 Cosmos 帳戶已就緒] 頁面。Wait for the portal to display the Congratulations! Your Cosmos account with wire protocol compatibility for MongoDB is ready page.

    Azure 入口網站的 [通知] 窗格

複製範例應用程式Clone the sample application

複製範例應用程式並安裝必要的套件。Clone the sample application and install the required packages.

  1. 在 GOROOT\src 資料夾 (預設為 C:\Go) 內建立名為 CosmosDBSample 的資料夾。Create a folder named CosmosDBSample inside the GOROOT\src folder, which is C:\Go\ by default.

  2. 使用 git 終端機視窗 (例如 git bash) 執行下列命令,將範例存放庫複製到 CosmosDBSample 資料夾中。Run the following command using a git terminal window such as git bash to clone the sample repository into the CosmosDBSample folder.

    git clone https://github.com/Azure-Samples/azure-cosmos-db-mongodb-golang-getting-started.git
    
  3. 執行下列命令以取得 mgo 套件。Run the following command to get the mgo package.

    go get gopkg.in/mgo.v2
    

mgo 驅動程式是 Go 語言MongoDB 驅動程式,它可在非常簡單且符合標準 Go 慣用語的 API 之下實作豐富且經過妥善測試的精選功能。The mgo driver is a MongoDB driver for the Go language that implements a rich and well tested selection of features under a very simple API following standard Go idioms.

更新您的連接字串Update your connection string

現在,返回 Azure 入口網站以取得連接字串資訊,並將它複製到應用程式中。Now go back to the Azure portal to get your connection string information and copy it into the app.

  1. 按一下左側導覽功能表中的 [快速入門],然後按一下 [其他] 以檢視 Go 應用程式所需的連接字串資訊。Click Quick start in the left navigation menu, and then click Other to view the connection string information required by the Go application.

  2. 在 Goglang 中,開啟 GOROOT\CosmosDBSample 目錄中的 main.go 檔案,並從 Azure 入口網站使用連接字串資訊來更新下列程式碼行,如下列螢幕擷取畫面所示。In Goglang, open the main.go file in the GOROOT\CosmosDBSample directory and update the following lines of code using the connection string information from the Azure portal as shown in the following screenshot.

    在 Azure 入口網站的連接字串窗格中,資料庫名稱是 [主機] 值的前置詞。The Database name is the prefix of the Host value in the Azure portal connection string pane. 針對下圖中顯示的帳戶,資料庫名稱是 golang-coach。For the account shown in the image below, the Database name is golang-coach.

    Database: "The prefix of the Host value in the Azure portal",
    Username: "The Username in the Azure portal",
    Password: "The Password in the Azure portal",
    

    Azure 入口網站中的 [快速入門] 窗格、顯示連接字串資訊的 [其他] 索引標籤

  3. 儲存 main.go 檔案。Save the main.go file.

檢閱程式碼Review the code

此為選用步驟。This step is optional. 若您想要瞭解如何在程式碼中建立資料庫資源,則可檢閱下列程式碼片段。If you're interested in learning how the database resources are created in the code, you can review the following snippets. 或是,您可以直接跳到執行應用程式Otherwise, you can skip ahead to Run the app.

下列程式碼片段全部取自 main.go 檔案。The following snippets are all taken from the main.go file.

將 Go 應用程式與 Cosmos DB 連線Connecting the Go app to Cosmos DB

Azure Cosmos DB 適用於 MongoDB 的 API 支援已啟用 SSL 的連線。Azure Cosmos DB's API for MongoDB supports the SSL-enabled connection. 若要連線,您需要在 mgo.DialInfo 中定義 DialServer 函式,並利用 tls.Dial 函式執行連線。To connect, you need to define the DialServer function in mgo.DialInfo, and make use of the tls.Dial function to perform the connection.

下列 Golang 程式碼片段會透過 Azure Cosmos DB 適用於 MongoDB 的 API 連線到 Go 應用程式。The following Golang code snippet connects the Go app with Azure Cosmos DB's API for MongoDB. DialInfo 類別保存可供建立工作階段的選項。The DialInfo class holds options for establishing a session.

// DialInfo holds options for establishing a session.
dialInfo := &mgo.DialInfo{
    Addrs:    []string{"golang-couch.documents.azure.com:10255"}, // Get HOST + PORT
    Timeout:  60 * time.Second,
    Database: "database", // It can be anything
    Username: "username", // Username
    Password: "Azure database connect password from Azure Portal", // PASSWORD
    DialServer: func(addr *mgo.ServerAddr) (net.Conn, error) {
        return tls.Dial("tcp", addr.String(), &tls.Config{})
    },
}

// Create a session which maintains a pool of socket connections
// to Cosmos database (using Azure Cosmos DB's API for MongoDB).
session, err := mgo.DialWithInfo(dialInfo)

if err != nil {
    fmt.Printf("Can't connect, go error %v\n", err)
    os.Exit(1)
}

defer session.Close()

// SetSafe changes the session safety mode.
// If the safe parameter is nil, the session is put in unsafe mode, 
// and writes become fire-and-forget,
// without error checking. The unsafe mode is faster since operations won't hold on waiting for a confirmation.
// 
session.SetSafe(&mgo.Safe{})

沒有 SSL 連線時會使用 mgo.Dial() 方法。The mgo.Dial() method is used when there is no SSL connection. SSL 連線需使用 mgo.DialWithInfo() 方法。For an SSL connection, the mgo.DialWithInfo() method is required.

DialWIthInfo{} 物件的執行個體用來建立工作階段物件。An instance of the DialWIthInfo{} object is used to create the session object. 一旦建立工作階段,您就可以使用下列程式碼片段來存取集合:Once the session is established, you can access the collection by using the following code snippet:

collection := session.DB("database").C("package")

建立文件Create a document

// Model
type Package struct {
    Id bson.ObjectId  `bson:"_id,omitempty"`
    FullName      string
    Description   string
    StarsCount    int
    ForksCount    int
    LastUpdatedBy string
}

// insert Document in collection
err = collection.Insert(&Package{
    FullName:"react",
    Description:"A framework for building native apps with React.",
    ForksCount: 11392,
    StarsCount:48794,
    LastUpdatedBy:"shergin",

})

if err != nil {
    log.Fatal("Problem inserting data: ", err)
    return
}

查詢或閱讀文件Query or read a document

Cosmos DB 支援針對每個集合中儲存的資料進行豐富查詢。Cosmos DB supports rich queries against data stored in each collection. 下列範例程式碼示範您可以針對集合中之文件執行的查詢。The following sample code shows a query that you can run against the documents in your collection.

// Get a Document from the collection
result := Package{}
err = collection.Find(bson.M{"fullname": "react"}).One(&result)
if err != nil {
    log.Fatal("Error finding record: ", err)
    return
}

fmt.Println("Description:", result.Description)

更新文件Update a document

// Update a document
updateQuery := bson.M{"_id": result.Id}
change := bson.M{"$set": bson.M{"fullname": "react-native"}}
err = collection.Update(updateQuery, change)
if err != nil {
    log.Fatal("Error updating record: ", err)
    return
}

刪除文件Delete a document

Cosmos DB 支援刪除文件。Cosmos DB supports deletion of documents.

// Delete a document
query := bson.M{"_id": result.Id}
err = collection.Remove(query)
if err != nil {
   log.Fatal("Error deleting record: ", err)
   return
}

執行應用程式Run the app

  1. 在 Golang 中,確定您的 GOPATH (可在 [檔案]、[設定]、[Go]、[GOPATH] 之下取得) 包含 gopkg 的安裝位置,預設為 USERPROFILE\go。In Golang, ensure that your GOPATH (available under File, Settings, Go, GOPATH) include the location in which the gopkg was installed, which is USERPROFILE\go by default.

  2. 將可刪除文件的程式碼行 (行 103-107) 註解化,以便在執行應用程式後查看文件。Comment out the lines that delete the document, lines 103-107, so that you can see the document after running the app.

  3. 在 Golang 中,按一下 [執行],然後按一下 [執行 [建置 main.go 並執行]]。In Golang, click Run, and then click Run 'Build main.go and run'.

    應用程式會完成並顯示在建立文件中建立之文件的說明。The app finishes and displays the description of the document created in Create a document.

    Description: A framework for building native apps with React.
    
    Process finished with exit code 0
    

    顯示應用程式輸出的 Golang

在資料總管中檢閱您的文件Review your document in Data Explorer

回到 Azure 入口網站,以在 [資料總管] 中查看您的文件。Go back to the Azure portal to see your document in Data Explorer.

  1. 按一下左側瀏覽功能表中的 [資料總管 (預覽)],展開 [golang-coach]、[套件],然後按一下 [文件]。Click Data Explorer (Preview) in the left navigation menu, expand golang-coach, package, and then click Documents. 在 [文件] 索引標籤上,按一下 _id 以在右窗格中顯示文件。In the Documents tab, click the _id to display the document in the right pane.

    顯示新建文件的資料總管

  2. 您可以接著使用內嵌的文件並按一下 [更新] 來儲存它。You can then work with the document inline and click Update to save it. 您也可以刪除文件,或建立新的文件或查詢。You can also delete the document, or create new documents or queries.

在 Azure 入口網站中檢閱 SLAReview SLAs in the Azure portal

Azure 入口網站會監視您的 Cosmos DB 帳戶輸送量、儲存體、可用性、延遲和一致性。The Azure portal monitors your Cosmos DB account throughput, storage, availability, latency, and consistency. Azure Cosmos DB 服務等級協定 (SLA) 相關聯的計量圖表會顯示相較於實際效能的 SLA 值。Charts for metrics associated with an Azure Cosmos DB Service Level Agreement (SLA) show the SLA value compared to actual performance. 此計量套件可讓您以更透明的方式監視監視 SLA。This suite of metrics makes monitoring your SLAs transparent.

若要檢閱計量和 SLA:To review metrics and SLAs:

  1. 在您的 Cosmos DB 帳戶導覽功能表中,選取 [計量] 。Select Metrics in your Cosmos DB account's navigation menu.

  2. 選取一個索引標籤 (例如 [延遲] ),並在右側選取時間範圍。Select a tab such as Latency, and select a timeframe on the right. 比較圖表中的實際SLA 的資料行。Compare the Actual and SLA lines on the charts.

    Azure Cosmos DB 計量套件

  3. 檢閱其他索引標籤中的計量。Review the metrics on the other tabs.

清除資源Clean up resources

完成您的 Web 應用程式和 Azure Cosmos DB 帳戶之後,您可以將建立的 Azure 資源刪除,以免產生更多費用。When you're done with your web 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, select Resource groups on the far left. 若已摺疊左側功能表,請選取展開按鈕加以展開。If the left menu is collapsed, select Expand button to expand it.

  2. 選取您在本快速入門中建立的資源群組。Select the resource group you created for this quickstart.

    Azure 入口網站中的計量

  3. 在新視窗中,選取 [刪除資源群組] 。In the new window, select Delete resource group.

    Azure 入口網站中的計量

  4. 在下個視窗中輸入要刪除的資源群組名稱,然後選取 [刪除] 。In the next window, enter the name of the resource group to delete, and then select Delete.

後續步驟Next steps

在本快速入門中,您已了解如何建立 Cosmos 帳戶及執行 Golang 應用程式。In this quickstart, you've learned how to create a Cosmos account and run a Golang app. 您現在可以將其他資料匯入到 Cosmos 資料庫。You can now import additional data to your Cosmos database.