在這個快速入門中,你會使用 Go 建立一個基本的 Azure DocumentDB 應用程式。 Azure DocumentDB 是一個 NoSQL 資料儲存庫,允許應用程式將文件儲存在雲端,並透過官方 MongoDB 驅動程式存取。 本指南說明如何使用 Go 在 Azure DocumentDB 叢集中建立文件並執行基本任務。
先決條件
Azure 訂用帳戶
- 如果您沒有 Azure 訂用帳戶,請建立 免費帳戶
- Golang 1.18 或更新版本
建立 Azure DocumentDB 叢集
要開始,你首先需要建立一個 Azure DocumentDB 叢集,作為儲存和管理 NoSQL 資料的基礎。
登入 Azure 入口網站 (https://portal.azure.com)。
從 Azure 入口網站功能表或 [首頁] 頁面,選取 [建立資源]。
在 新頁面 搜尋並選擇 Azure DocumentDB。
在「建立 Azure DocumentDB 叢集」頁面及「基礎」區塊中,選擇叢集層級區塊中的「配置」選項。
在 縮放 頁面中,設定這些選項,然後選擇 儲存 ,將你的變更永久化到叢集層級。
價值觀 叢集層 M30 tier, 2 vCore, 8-GiB RAM每個分區的儲存體 128 GiB
回到 基礎 部分,設定以下選項:
價值觀 Subscription 選取您的 Azure 訂用帳戶 資源群組 建立新的資源群組,或選取現有的資源群組 叢集名稱 提供全域唯一名稱 地點 為您的訂用帳戶選取支援的 Azure 區域 MongoDB 版本 選取 8.0系統管理員使用者名稱 建立使用者名稱以以使用者管理員身份存取叢集 密碼 使用與使用者名稱相關的獨特密碼
小提示
記錄你用來輸入 使用者名稱 和 密碼的數值。 這些數值會在本指南後面使用。 關於有效數值的更多資訊,請參見 叢集限制。
請選取「下一步:網路」。
在網路標籤的防火牆規則區塊中,設定以下選項:
價值觀 連線方法 Public access允許從 Azure 內的服務和資源對此叢集進行公開存取 Enabled 為你目前的客戶端裝置新增防火牆規則,透過選擇 + 新增目前的客戶端 IP 位址來授權存取叢集。
小提示
在許多公司環境中,開發人員機器 IP 位址會因為 VPN 或其他公司網路設定而遭到隱藏。 在這種情況下,你可以透過新增一個包含
0.0.0.0-255.255.255.255的 IP 位址範圍至防火牆規則中,來暫時允許所有 IP 位址的存取。 此防火牆規則僅暫時用於連線測試與開發。選擇 檢閱 + 創建。
檢閱您提供的設定,然後選取 建立。 建立叢集需要幾分鐘的時間。 等待資源部署完成。
最後,選擇 「前往資源 」以導航至入口網站中的 Azure DocumentDB 叢集。
取得叢集認證
取得你用來連接叢集的憑證。
在叢集頁面,選擇資源選單中的 連線字串 選項。
在 Connection 字串 區塊,複製或記錄 Connection 字串 欄位的值。
這很重要
入口網站中的連接字串不包含密碼值。 您必須將 <password> 佔位符替換為建立叢集時輸入的憑證,或以互動方式輸入密碼。
初始化專案
在你目前的目錄中建立一個新的 Go 模組。
從空白目錄開始。
在目前目錄中開啟終端機。
初始化新的 Go 模組。
go mod init azure-documentdb-go-quickstart
安裝用戶端程式庫
用戶端函式庫可透過 Go go.mongodb.org/mongo-driver/v2/mongo 作為模組取得。
使用
go get安裝 MongoDB Go 驅動程式。go get go.mongodb.org/mongo-driver/v2/mongo建立一個新的
main.goGo 檔案,命名為你的應用程式代碼。將所需的套件匯入您的應用程式碼:
import ( "context" "fmt" "log" "time" "go.mongodb.org/mongo-driver/v2/bson" "go.mongodb.org/mongo-driver/v2/mongo" "go.mongodb.org/mongo-driver/v2/mongo/options" )
物件模型
| 名稱 | Description |
|---|---|
mongo.Client |
用來連線到 MongoDB 的類型。 |
mongo.Database |
表示叢集中的資料庫。 |
mongo.Collection |
表示叢集中資料庫內的集合。 |
程式碼範例
此應用程式中的程式碼連接一個名為 adventureworks 的資料庫與一個名為 products的集合。 該 products 收藏包含名稱、類別、數量、獨特識別碼及每項產品的銷售標誌等細節。 這裡的程式碼範例執行在處理集合時最常見的操作。
驗證用戶端
首先,使用基本的連接字串連接到用戶端。
建立主要函式並設定連接字串。 將
<your-cluster-name>、<your-username>和<your-password>替換為您實際的叢集資訊。func main() { // Connection string for Azure DocumentDB cluster connectionString := "mongodb+srv://<your-username>:<your-password>@<your-cluster-name>.global.mongocluster.cosmos.azure.com/?tls=true&authMechanism=SCRAM-SHA-256&retrywrites=false&maxIdleTimeMS=120000" // Create client options clientOptions := options.Client().ApplyURI(connectionString)連接到 MongoDB 用戶端並驗證連線。
// Create a new client and connect to the server ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() client, err := mongo.Connect(ctx, clientOptions) if err != nil { log.Fatal(err) } defer client.Disconnect(ctx) // Ping the primary err = client.Ping(ctx, nil) if err != nil { log.Fatal(err) } fmt.Println("Successfully connected and pinged Azure DocumentDB")
取得集合
現在,取得您的資料庫和集合。 如果資料庫和集合還不存在,可以用驅動程式自動幫你建立。
取得資料庫的參考資料。
// Get database reference database := client.Database("adventureworks") fmt.Println("Connected to database:", database.Name())取得資料庫內的集合參考。
// Get collection reference collection := database.Collection("products") fmt.Println("Connected to collection:", collection.Name())
建立文件
接著,在你的收藏中新增幾份文件。 將文件 upsert 或更新,以確保若已存在具有相同唯一識別碼的文件,則會取代此文件。
定義產品類型並建立範例產品文件。
type Product struct { ID string `bson:"_id,omitempty"` Name string `bson:"name"` Category string `bson:"category"` Quantity int `bson:"quantity"` Price float64 `bson:"price"` Sale bool `bson:"sale"` } // Create sample products products := []Product{ { ID: "00000000-0000-0000-0000-000000004018", Name: "Windry Mittens", Category: "apparel-accessories-gloves-and-mittens", Quantity: 121, Price: 35.00, Sale: false, }, { ID: "00000000-0000-0000-0000-000000004318", Name: "Niborio Tent", Category: "gear-camp-tents", Quantity: 140, Price: 420.00, Sale: true, }, }使用 upsert 作業插入文件。
// Insert documents with upsert for _, product := range products { filter := bson.M{"_id": product.ID} update := bson.M{"$set": product} opts := options.Update().SetUpsert(true) result, err := collection.UpdateOne(ctx, filter, update, opts) if err != nil { log.Fatal(err) } if result.UpsertedID != nil { fmt.Printf("Inserted document with ID: %v\n", result.UpsertedID) } else { fmt.Printf("Updated document with ID: %s\n", product.ID) } }
擷取文件
接著,執行點讀取操作,從你的收藏中擷取特定文件。
定義篩選器,透過 ID 尋找特定文件。
// Retrieve a specific document by ID filter := bson.M{"_id": "00000000-0000-0000-0000-000000004018"} var retrievedProduct Product執行查詢並解碼結果。
err = collection.FindOne(ctx, filter).Decode(&retrievedProduct) if err != nil { log.Fatal(err) } fmt.Printf("Retrieved product: %+v\n", retrievedProduct)
查詢文件
最後,使用 MongoDB 查詢語言(MQL)查詢多份文件。
定義一個查詢以尋找符合特定條件的文件。
// Query for products on sale queryFilter := bson.M{"sale": true} cursor, err := collection.Find(ctx, queryFilter) if err != nil { log.Fatal(err) } defer cursor.Close(ctx)透過游標遍歷以取得所有符合的相關文件。
fmt.Println("Products on sale:") for cursor.Next(ctx) { var product Product if err := cursor.Decode(&product); err != nil { log.Fatal(err) } fmt.Printf("- %s: $%.2f (Category: %s)\n", product.Name, product.Price, product.Category) } if err := cursor.Err(); err != nil { log.Fatal(err) } }
使用 Visual Studio Code 探索您的資料
在 Visual Studio Code 中使用 DocumentDB 擴充功能來執行核心資料庫操作,包括查詢、插入、更新及刪除資料。
開啟 Visual Studio Code。
請導覽至 擴充功能 檢視並搜尋該詞
DocumentDB。 請找到 DocumentDB for VS Code 擴充功能。選擇擴充功能的 安裝 按鈕。 等候安裝完成。 如果系統提示,請重新載入 Visual Studio Code。
請在活動欄中選擇對應圖示,導向 DocumentDB 擴充功能。
在 DocumentDB 連接 面板中,選擇 + 新連線...。
在對話框中,選擇 Service Discovery ,然後選擇 Azure DocumentDB - Azure Service Discovery。
選擇您的 Azure 訂閱及新建立的 Azure DocumentDB 叢集。
小提示
在許多公司環境中,開發人員機器 IP 位址會因為 VPN 或其他公司網路設定而遭到隱藏。 在這種情況下,你可以透過新增一個包含
0.0.0.0-255.255.255.255的 IP 位址範圍至防火牆規則中,來暫時允許所有 IP 位址的存取。 此防火牆規則僅暫時用於連線測試與開發。 如需詳細資訊,請參閱 設定防火牆。回到 DocumentDB 的連接 面板,展開叢集節點,並導覽到現有的文件和集合節點。
打開該收藏的右鍵選單,然後選擇 DocumentDB 剪貼簿 > 新設 DocumentDB 剪貼簿。
輸入以下 MongoDB 查詢語言(MQL)指令,然後選擇「全部執行」。 觀察指令的輸出。
db.products.find({ price: { $gt: 200 }, sale: true }) .sort({ price: -1 }) .limit(3)
清理資源
完成 Azure DocumentDB 叢集後,你可以刪除你建立的 Azure 資源,避免額外收費。
在 Azure 入口網站的搜尋列中,搜尋並選取 [資源群組]。
在清單中,選取您在此快速入門中使用的資源群組。
在 [資源群組] 頁面中,選取 [刪除資源群組]。
在刪除確認對話方塊中,輸入資源群組的名稱,以確認您要將其刪除。 最後,選取 [刪除] 以永久刪除資源群組。