你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn。
快速入门:适用于 Node.js 的适合 MongoDB 的 Azure Cosmos DB 驱动程序
适用对象: MongoDB
开始使用 MongoDB npm 包在 Azure Cosmos DB 资源中创建数据库、集合和文档。 请按照以下步骤安装程序包并试用基本任务的示例代码。
注意
示例代码片段在 GitHub 上作为 JavaScript 项目提供。
API for MongoDB 参考文档 | MongoDB 包 (NuGet)
先决条件
- 具有活动订阅的 Azure 帐户。 免费创建帐户。
- Node.js LTS
- Azure 命令行接口 (CLI) 或 Azure PowerShell
先决条件检查
- 在终端或命令窗口中,运行
node --version
以检查 Node.js 是否是 LTS 版本之一。 - 运行
az --version
(Azure CLI) 或Get-Module -ListAvailable AzureRM
(Azure PowerShell),检查是否安装了适当的 Azure 命令行工具。
设置
本部分引导你创建 Azure Cosmos DB 帐户并设置使用 MongoDB npm 包的项目。
创建 Azure Cosmos DB 帐户
本快速入门将使用 API for MongoDB 创建单个 Azure Cosmos DB 帐户。
为 accountName、resourceGroupName 和 location 创建 shell 变量。
# Variable for resource group name resourceGroupName="msdocs-cosmos-quickstart-rg" location="westus" # Variable for account name with a randomnly generated suffix let suffix=$RANDOM*$RANDOM accountName="msdocs-$suffix"
如果尚未登录,请使用
az login
命令登录到 Azure CLI。使用
az group create
命令在订阅中创建新的资源组。az group create \ --name $resourceGroupName \ --location $location
使用
az cosmosdb create
命令创建具有默认设置的新 Azure Cosmos DB for MongoDB 帐户。az cosmosdb create \ --resource-group $resourceGroupName \ --name $accountName \ --locations regionName=$location --kind MongoDB
获取 MongoDB 连接字符串
使用
az cosmosdb keys list
命令,从帐户的连接字符串列表中查找 API for MongoDB 连接字符串。az cosmosdb keys list --type connection-strings \ --resource-group $resourceGroupName \ --name $accountName
请记下“主密钥”值。 稍后将使用这些凭据。
创建新的 JavaScript 应用
使用首选终端在空文件夹中创建新的 JavaScript 应用程序。 使用 npm init
命令开始提示用户创建 package.json
文件。 接受提示的默认值。
npm init
安装包
将 MongoDB npm 包添加到 JavaScript 项目。 使用 npm install package
命令指定 npm 包的名称。 dotenv
包用于在本地开发期间从 .env
文件中读取环境变量。
npm install mongodb dotenv
配置环境变量
若要在代码中使用“连接字符串”值,请在运行应用程序的本地环境中设置此值。 若要设置环境变量,请使用首选终端运行以下命令:
$env:COSMOS_CONNECTION_STRING = "<cosmos-connection-string>"
对象模型
在开始构建应用程序之前,我们先来了解 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
集合设计为包含产品详细信息,例如名称、类别、数量和销售指标。 每个产品还包含一个唯一标识符。
对于此过程,数据库不会使用分片。
验证客户端
在项目目录中创建 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');
使用构造函数定义
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
方法连接到 Azure Cosmos DB for MongoDB 资源。 connect 方法返回对数据库的引用。
// 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
在集合中创建文档。 在此示例中,我们选择了更新插入而不是创建新文档,因为需要运行此示例代码多次。
获取文档
在 Azure Cosmos DB 中,可同时使用唯一标识符 (_id
) 和分区键 (category
) 来执行低开销的点读取操作。
// 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 资源。