在本快速入门中,你将使用 .NET 部署基本的 Azure Cosmos DB for MongoDB vCore 应用程序。 Azure Cosmos DB for MongoDB vCore 是一种无架构数据存储,允许应用程序使用 MongoDB 库将非结构化文档存储在云中。 了解如何使用 .NET 在 Azure Cosmos DB 资源中创建文档和执行基本任务。
库源代码 | 包 (NuGet) | Azure Developer CLI
Azure 开发人员 CLI
Docker Desktop
Azure 订阅服务
- 如果没有 Azure 订阅,可在开始前创建一个试用帐户。
- .NET SDK 9.0
使用 Azure 开发人员 CLI (azd
) 创建 Azure Cosmos DB for MongoDB vCore 群集并部署容器化示例应用程序。 示例应用程序使用客户端库来管理、创建、读取和查询示例数据。
在空目录中打开终端。
如果尚未经过身份验证,请使用
azd auth login
向 Azure Developer CLI 进行身份验证。 按照工具指定的步骤,使用首选的 Azure 凭据向 CLI 进行身份验证。azd auth login
使用
azd init
来初始化项目。azd init --template cosmos-db-mongodb-vcore-dotnet-quickstart
在初始化期间,配置唯一的环境名称。
使用
azd up
. 部署群集。 Bicep 模板还部署示例 Web 应用程序。azd up
在预配过程中,选择订阅、所需位置和目标资源组。 等待预配过程完成。 此过程可能需要大约 5 分钟。
预配 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.
使用控制台中的 URL 在浏览器中导航到 Web 应用程序。 观察正在运行的应用的输出。
客户端库可通过 NuGet 作为 MongoDB.Driver
包使用。 若要Microsoft Entra 身份验证,请使用 Azure.Identity
适用于 .NET 的 Azure SDK 中的包。
打开终端并导航到
/src/web
文件夹。cd ./src/web
使用
MongoDB.Driver
安装dotnet add package
包(如果尚未安装)。dotnet add package MongoDB.Driver
如果尚未安装,请安装
Azure.Identity
包。dotnet add package Azure.Identity
打开并查看 src/api/Microsoft.Learn.AzureCosmosDBMongoDBQuickstart.Api.csproj 文件,以验证这两个包条目是否存在。
将以下命名空间导入应用程序代码:
包装 | 来源 | |
---|---|---|
Azure.Core |
Azure.Identity |
用于 .NET 的 Azure SDK |
Azure.Identity |
Azure.Identity |
用于 .NET 的 Azure SDK |
MongoDB.Driver |
MongoDB.Driver |
适用于 .NET 的官方 MongoDB 驱动程序 |
MongoDB.Driver.Authentication.Oidc |
MongoDB.Driver |
适用于 .NET 的官方 MongoDB 驱动程序 |
using Azure.Core;
using Azure.Identity;
using MongoDB.Driver;
using MongoDB.Driver.Authentication.Oidc;
名称 | DESCRIPTION |
---|---|
MongoClient |
用于连接到 MongoDB 的类型。 |
Database |
表示群集上的数据库。 |
Collection |
表示群集上的数据库中的集合。 |
模板中的示例代码使用名为 cosmicworks
的数据库和名为 products
的集合。
products
集合包含每个产品的名称、类别、数量和唯一标识符等详细信息。 该集合使用 /category
属性作为分片键。
虽然 Azure Cosmos DB for MongoDB vCore 的 Microsoft Entra 身份验证可以使用众所周知的 TokenCredential
类型,但你必须实现自定义令牌处理程序。 此示例实现可用于创建 MongoClient
,以支持多种标识类型的标准 Microsoft Entra 身份验证。
首先,在实现
IOidcCallback
接口的单独文件中创建新类。using Azure.Core; using MongoDB.Driver.Authentication.Oidc; internal sealed class AzureIdentityTokenHandler( TokenCredential credential, string tenantId ) : IOidcCallback { private readonly string[] scopes = ["https://ossrdbms-aad.database.chinacloudapi.cn/.default"]; public OidcAccessToken GetOidcAccessToken(OidcCallbackParameters parameters, CancellationToken cancellationToken) { AccessToken token = credential.GetToken( new TokenRequestContext(scopes, tenantId: tenantId), cancellationToken ); return new OidcAccessToken(token.Token, token.ExpiresOn - DateTimeOffset.UtcNow); } public async Task<OidcAccessToken> GetOidcAccessTokenAsync(OidcCallbackParameters parameters, CancellationToken cancellationToken) { AccessToken token = await credential.GetTokenAsync( new TokenRequestContext(scopes, parentRequestId: null, tenantId: tenantId), cancellationToken ); return new OidcAccessToken(token.Token, token.ExpiresOn - DateTimeOffset.UtcNow); } }
创建自定义处理程序类的新实例,传入
DefaultAzureCredential
类型的新实例和你的租户 ID。DefaultAzureCredential credential = new(); string tenantId = "<microsoft-entra-tenant-id>"; AzureIdentityTokenHandler tokenHandler = new(credential, tenantId);
使用你最近部署的 Azure Cosmos DB for MongoDB vCore 实例的终结点和方案创建
MongoUrl
的实例。string clusterName = "<azure-cosmos-db-mongodb-vcore-cluster-name>"; MongoUrl url = MongoUrl.Create($"mongodb+srv://{clusterName}.global.mongocluster.cosmos.azure.com/");
使用 Azure Cosmos DB for MongoDB vCore 的已知最佳做法配置选项以及自定义的
MongoClient
实现来配置IOidcCallback
实例。MongoClientSettings settings = MongoClientSettings.FromUrl(url); settings.UseTls = true; settings.RetryWrites = false; settings.MaxConnectionIdleTime = TimeSpan.FromMinutes(2); settings.Credential = MongoCredential.CreateOidcCredential(tokenHandler); settings.Freeze(); MongoClient client = new(settings);
此示例使用 IMongoDatabase
类的 GetDatabase
方法创建 MongoClient
接口的实例。
IMongoDatabase database = client.GetDatabase("<database-name>");
此示例使用 IMongoCollection<>
接口的 GetCollection<>
泛型方法创建泛型 IMongoDatabase
接口的实例。 泛型接口和方法都使用另一类中定义的类型 Product
。
IMongoCollection<Product> collection = database.GetCollection<Product>("<collection-name>");
public record Product(
string id,
string category,
string name,
int quantity,
decimal price,
bool clearance
);
使用 collection.ReplaceOneAsync<>
和泛型 Product
类型参数在集合中创建文档。 如果文档已存在于集合中,此方法将有效地替换它。
Product document = new(
id: "aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb",
category: "gear-surf-surfboards",
name: "Yamba Surfboard",
quantity: 12,
price: 850.00m,
clearance: false
);
await collection.ReplaceOneAsync<Product>(
doc => doc.id == document.id,
document,
new ReplaceOptions { IsUpsert = true }
);
使用文档的唯一标识符 (id
) 执行读取操作。 与 collection.FindAsync<>
泛型 Product
类型参数一起使用以有效检索特定文档。
Product? document = await collection.Find(
doc => doc.id == "aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb"
).SingleOrDefaultAsync();
使用 collection.AsQueryable()
语言集成查询(LINQ)对容器中的多个文档执行查询。 此查询用于查找指定类别(分片键)内的所有文档。
List<Product> documents = await collection.Find(
filter: doc => doc.category == "gear-surf-surfboards"
).ToListAsync();
foreach (Product document in documents)
{
// Do something with each document
}
通过发送一个包含文档唯一标识符的筛选器来删除文档。 使用 collection.DeleteOneAsync<>
来异步地将文档从集合中删除。
await collection.DeleteOneAsync(
doc => doc.id == "aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb"
);
使用适用于 Azure Cosmos DB 的 Visual Studio Code 扩展浏览 MongoDB vCore 数据。 可以执行核心数据库操作,这些操作包括但不限于:
- 使用剪贴簿或查询编辑器执行查询
- 修改、更新、创建和删除文档
- 从其他源导入批量数据
- 管理数据库和集合
有关详细信息,请参阅 如何使用 Visual Studio Code 扩展浏览 Azure Cosmos DB for MongoDB vCore 数据。
不再需要示例应用程序或资源时,请删除相应的部署和所有资源。
azd down --force