快速入門:適用於 Node.js 的 Azure Cosmos DB for MongoDB 驅動程式

適用於: MongoDB

開始使用 MongoDB npm 套件,以在您的 Azure Cosmos DB 資源內建立資料庫、集合和文件。 請遵循下列步驟來安裝套件,並試用基本工作的程式碼範例。

注意

範例程式碼片段可在 GitHub 上以 JavaScript 專案形式取得。

適用於 MongoDB 的 API 參考檔 | MongoDB 套件 (NuGet) 套件/Microsoft.Azure.Cosmos) | Azure 開發人員 CLI

必要條件

設定

將這個專案的開發容器部署到您的環境。 然後,使用 Azure 開發人員 CLI (azd) 建立適用於 MongoDB 的 Azure Cosmos DB 帳戶,並部署容器化範例應用程式。 應用程式範例使用用戶端程式庫管理、建立、讀取和查詢樣本資料。

在 GitHub Codespaces 中開啟

在開發容器中開啟

重要

GitHub 帳戶的免費權利包括儲存體和核心時數。 如需詳細資訊,請參閱 GitHub 帳戶包含的儲存體和核心時數

  1. 在專案的根目錄中開啟終端。

  2. 使用 azd auth login 以向 Azure Developer CLI 進行驗證。 依照工具指定的步驟,使用您慣用的 Azure 認證向 CLI 進行驗證。

    azd auth login
    
  3. 使用 azd init 來初始化專案。

    azd init
    
  4. 在初始化期間,請設定唯一的環境名稱。

    提示

    環境名稱也將是目標資源群組名稱。 在這個快速入門中,請考慮使用 msdocs-cosmos-db

  5. 使用 azd up部署 Azure Cosmos DB 帳戶。 Bicep 範本也會部署範例 Web 應用程式。

    azd up
    
  6. 在佈建流程期間,請選取您的訂用帳戶和所需位置。 等候佈建程序完成。 此流程「大約需要五分鐘」的時間。

  7. Azure 資源佈建完成後,輸出將包含正在執行的 Web 應用程式的 URL。

    Deploying services (azd deploy)
    
      (✓) Done: Deploying service web
    - Endpoint: <https://[container-app-sub-domain].azurecontainerapps.io>
    
    SUCCESS: Your application was provisioned and deployed to Azure in 5 minutes 0 seconds.
    
  8. 請使用主控台中的 URL,以在瀏覽器中導覽至您的 Web 應用程式。 觀察執行中應用程式的輸出。

    執行中 Web 應用程式的螢幕快照。


Install the package

MongoDB npm 套件新增至 JavaScript 專案。 使用 npm install package 命令,指定 npm 套件的名稱。 在本機部署期間,會使用 dotenv 套件來讀取 .env 檔案中的環境變數。

npm install mongodb dotenv

物件模型

在開始建置應用程式之前,讓我們看一下 Azure Cosmos DB 中的資源階層。 Azure Cosmos DB 具有用來建立和存取資源的特定物件模型。 Azure Cosmos DB 會在由帳戶、資料戶、集合和文件所組成的階層中建立資源。

Azure Cosmos DB 階層的圖表,包括帳戶、資料庫、集合和檔。

在頂端顯示 Azure Cosmos DB 帳戶的階層式圖表。 帳戶有兩個子資料庫分區。 其中一個資料庫分區包含兩個子集合分區。 另一個資料庫分區包含單一子集合節點。 該單一集合分區有三個子文件分區。

您將使用下列 MongoDB 類別與這些資源互動:

  • MongoClient - 此類別提供 Azure Cosmos DB 上 API for MongoDB 層的用戶端邏輯表示法。 用戶端物件會用於設定及執行針對服務的要求。
  • Db - 此類別是服務中可能存在或不存在的資料庫參考。 當您嘗試存取資料庫或對其執行作業時,資料庫為已驗證的伺服器端。
  • Collection - 此類別為集合參考,可能尚未存在於伺服器中。 當您嘗試使用集合時,集合為已驗證的伺服器端。

程式碼範例

本文所述的範例程式碼會建立名為 adventureworks 的資料庫,其中包含名為 products 的集合。 products 集合的設計目的是要包含產品詳細資料,例如名稱、類別、數量和銷售指標。 每個產品也都包含唯一識別碼。

在此程序中,資料庫將不會使用分區。

驗證用戶端

  1. 從專案目錄中,建立 index.js 檔案。 在您的編輯器中,新增 Requires 陳述式以參考 MongoDB 和 DotEnv npm 套件。

    // Read .env file and set environment variables
    require('dotenv').config();
    const random = Math.floor(Math.random() * 100);
    
    // Use official mongodb driver to connect to the server
    const { MongoClient, ObjectId } = require('mongodb');
    
  2. 使用建構函式定義 MongoClient, 類別的新執行個體,並使用 process.env. 讀取您稍早建立的環境變數。

    // New instance of MongoClient with connection string
    // for Cosmos DB
    const url = process.env.COSMOS_CONNECTION_STRING;
    const client = new MongoClient(url);
    

如需以不同方式建立 MongoClient 執行個體的詳細資訊,請參閱 MongoDB NodeJS 驅動程式快速入門

設定非同步作業

index.js 檔案中,新增下列程式碼以支援非同步作業:

async function main(){

// The remaining operations are added here
// in the main function

}

main()
  .then(console.log)
  .catch(console.error)
  .finally(() => client.close());

下列程式碼片段應該新增至 main 函式,以處理 async/await 語法。

連線至資料庫

使用 MongoClient.connect 方法,連接至適用於 MongoDB 的 Azure Cosmos DB 資源。 此連接方法會傳回資料庫的參考。

// Use connect method to connect to the server
await client.connect();

取得資料庫執行個體

使用 MongoClient.db 取得資料庫的參考。

// Database reference with creation if it does not already exist
const db = client.db(`adventureworks`);
console.log(`New database:\t${db.databaseName}\n`);

取得集合執行個體

MongoClient.Db.collection 取得集合的參考。

// Collection reference with creation if it does not already exist
const collection = db.collection('products');
console.log(`New collection:\t${collection.collectionName}\n`);

鏈結的執行個體

您可以將用戶端、資料庫和集合鏈結在一起。 如果您需要存取多個資料庫或集合,則鏈結更為方便。

const db = await client.db(`adventureworks`).collection('products').updateOne(query, update, options)

建立索引

使用 Collection.createIndex,在您想要用於使用 MongoDB FindCursor.sort 方法排序的文件屬性上建立索引。

// create index to sort by name
const indexResult = await collection.createIndex({ name: 1 });
console.log(`indexResult: ${JSON.stringify(indexResult)}\n`);

建立文件

使用 adventureworks 資料庫的 product 屬性來建立文件:

  • 產品唯一識別碼的 _id 屬性。
  • category 屬性。 此屬性可作為邏輯分割區索引鍵。
  • name 屬性。
  • 庫存 quantity 屬性。
  • sale 屬性,指出產品是否正在銷售。
// Create new doc and upsert (create or replace) to collection
const product = {
    category: "gear-surf-surfboards",
    name: `Yamba Surfboard-${random}`,
    quantity: 12,
    sale: false
};
const query = { name: product.name};
const update = { $set: product };
const options = {upsert: true, new: true};

// Insert via upsert (create or replace) doc to collection directly
const upsertResult1 = await collection.updateOne(query, update, options);
console.log(`upsertResult1: ${JSON.stringify(upsertResult1)}\n`);

// Update via upsert on chained instance
const query2 = { _id: ObjectId(upsertResult1.upsertedId) };
const update2 = { $set: { quantity: 20 } };
const upsertResult2 = await client.db(`adventureworks`).collection('products').updateOne(query2, update2, options);
console.log(`upsertResult2: ${JSON.stringify(upsertResult2)}\n`);

藉由呼叫 Collection.UpdateOne,在集合中建立文件。 在此範例中,我們選擇 upsert 而不是 create 新文件,以避免您重複執行此範例程式碼。

取得文件

在 Azure Cosmos DB 中,您可以使用唯一識別碼 (_id) 和分割區索引鍵 (category) 來執行成本較低的點讀取 (Point Read) 作業。

// Point read doc from collection:
// - without sharding, should use {_id}
// - with sharding,    should use {_id, partitionKey }, ex: {_id, category}
const foundProduct = await collection.findOne({
    _id: ObjectId(upsertResult1.upsertedId), 
    category: "gear-surf-surfboards"
});
console.log(`foundProduct: ${JSON.stringify(foundProduct)}\n`);

查詢文件

插入文件之後,您可以執行查詢來取得符合特定篩選的所有文件。 此範例會尋找符合特定類別的所有文件:gear-surf-surfboards。 定義查詢之後,請呼叫 Collection.find 以取得 FindCursor 結果。 將資料指標轉換成陣列,以使用 JavaScript 陣列方法。

// select all from product category
const allProductsQuery = { 
    category: "gear-surf-surfboards" 
};

// get all documents, sorted by name, convert cursor into array
const products = await collection.find(allProductsQuery).sort({name:1}).toArray();
products.map((product, i ) => console.log(`${++i} ${JSON.stringify(product)}`));

疑難排解:

  • 如果您收到 The index path corresponding to the specified order-by item is excluded. 這類錯誤,則請確定您已建立索引

執行程式碼

此應用程式會建立 API for MongoDB 資料庫和集合,並建立文件,然後重新讀取完全相同的文件。 最後,此範例會發出只應傳回該單一文件的查詢。在每個步驟中,範例會將資訊輸出至主控台,包含其執行的步驟。

若要執行應用程式,請使用終端機瀏覽至應用程式目錄並執行應用程式。

node index.js

此命令的輸出應類似此範例:

New database:   adventureworks

New collection: products

upsertResult1: {"acknowledged":true,"modifiedCount":0,"upsertedId":"62b1f492ff69395b30a03169","upsertedCount":1,"matchedCount":0}

upsertResult2: {"acknowledged":true,"modifiedCount":1,"upsertedId":null,"upsertedCount":0,"matchedCount":1}

foundProduct: {"_id":"62b1f492ff69395b30a03169","name":"Yamba Surfboard-93","category":"gear-surf-surfboards","quantity":20,"sale":false}

indexResult: "name_1"

1 {"_id":"62b1f47dacbf04e86c8abf25","name":"Yamba Surfboard-11","category":"gear-surf-surfboards","quantity":20,"sale":false}
done

清除資源

當您不再需要 Azure Cosmos DB for MongoDB 帳戶時,可以刪除對應的資源群組。

使用 az group delete 命令以刪除資源群組。

az group delete --name $resourceGroupName

下一步

在此快速入門中,您已了解如何使用 MongoDB 驅動程式來建立 Azure Cosmos DB for MongoDB 帳戶、建立資料庫,以及建立集合。 您現在可以深入了解 Azure Cosmos DB for MongoDB,以匯入更多資料、執行複雜的查詢,以及管理 Azure Cosmos DB MongoDB 資源。