对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。
Docs 菜单

快速入门

本指南向您展示如何创建使用 .NET/C# 驱动程序连接到 MongoDB Atlas 集群的应用程序。如果希望使用其他驱动程序或编程语言连接到 MongoDB,请参阅我们的 MongoDB 官方驱动程序列表。

.NET/C# 驱动程序允许您从 .NET/C# 应用程序连接到 MongoDB 集群并与之通信。

MongoDB Atlas 是完全托管的云数据库服务,可在 MongoDB 集群托管数据。 在本指南中,我们将向您介绍 如何开始使用自己的免费(无需信用卡)集群。

按照以下步骤将 .NET 应用程序与 MongoDB Atlas 集群进行连接。

如需设置本指南所需的“Atlas 免费层级集群”,请完成 MongoDB Atlas 设置指南。

完成 Atlas 指南中的步骤后,您将在 Atlas 部署一个新的 MongoDB 集群、一个新的数据库用户,并将示例数据集加载到此集群。复制缓冲区还有一个类似于以下内容的连接字符串:

"mongodb+srv://<db_username>:<db_password>@cluster0.abc.mongodb.net/?retryWrites=true&w=majority"

在命令提示符处运行以下代码,将 MongoDB 连接字符串保存到环境变量中。该方法比在源代码中包含凭证更安全。

export MONGODB_URI="<your MongoDB URI>"

注意

PowerShell 环境变量

如果使用的是 Microsoft PowerShell,请运行以下命令,将连接字符串保存在环境变量中:

set MONGODB_URI="<your MongoDB URI>"

重要

确保使用 Atlas 数据库用户的用户名和密码替换连接字符串中的 <db_username><db_password> 部分。

有关连接字符串的更多信息,请参阅连接字符串。

创建一个新目录并使用 dotnet new 命令初始化项目,如下所示:

mkdir csharp-quickstart
cd csharp-quickstart
dotnet new console

使用 dotnet add 命令将 .NET/C# 驱动程序作为依赖项添加到项目中。

dotnet add package MongoDB.Driver

将以下代码复制并粘贴到应用程序的 Program.cs文件中。您可以选择使用 BsonDocument 或普通旧 CLR 对象 (POCO) 来查询文档。选择相应的标签页,查看每种方法的示例:

using MongoDB.Bson;
using MongoDB.Bson.IO;
using MongoDB.Driver;
var connectionString = Environment.GetEnvironmentVariable("MONGODB_URI");
if (connectionString == null)
{
Console.WriteLine("You must set your 'MONGODB_URI' environment variable. To learn how to set it, see https://www.mongodb.com/zh-cn/docs/drivers/csharp/current/get-started/create-connection-string");
Environment.Exit(0);
}
var client = new MongoClient(connectionString);
var collection = client.GetDatabase("sample_mflix").GetCollection<BsonDocument>("movies");
var filter = Builders<BsonDocument>.Filter.Eq("title", "Back to the Future");
var document = collection.Find(filter).First();
Console.WriteLine(document.ToJson(new JsonWriterSettings { Indent = true }));
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Driver;
var connectionString = Environment.GetEnvironmentVariable("MONGODB_URI");
if (connectionString == null)
{
Console.WriteLine("You must set your 'MONGODB_URI' environment variable. To learn how to set it, see https://www.mongodb.com/zh-cn/docs/drivers/csharp/current/get-started/create-connection-string");
Environment.Exit(0);
}
var client = new MongoClient(connectionString);
var collection = client.GetDatabase("sample_mflix").GetCollection<Movie>("movies");
var filter = Builders<Movie>.Filter.Eq(m => m.Title, "Back to the Future");
var movie = collection.Find(filter).First();
Console.WriteLine($"Title: {movie.Title}");
Console.WriteLine($"Plot: {movie.Plot}");
Console.WriteLine($"Genres: {string.Join(", ", movie.Genres ?? [])}");
[BsonIgnoreExtraElements]
public class Movie
{
[BsonId]
public ObjectId Id { get; set; }
[BsonElement("title")]
public string? Title { get; set; }
[BsonElement("plot")]
public string? Plot { get; set; }
[BsonElement("genres")]
public List<string>? Genres { get; set; }
}

提示

要学习有关将 POCO 与 .NET/C# 驱动程序结合使用的更多信息,请参阅 POCO 指南。

在命令行中,使用以下命令运行应用程序:

dotnet run csharp-quickstart.csproj

输出包括检索到的电影文档的详细信息。以下显示了每种方法的输出:

{
_id: ...,
plot: 'A young man is accidentally sent 30 years into the past...',
genres: [ 'Adventure', 'Comedy', 'Sci-Fi' ],
...
title: 'Back to the Future',
...
}
Title: Back to the Future
Plot: A young man is accidentally sent 30 years into the past...
Genres: Adventure, Comedy, Sci-Fi

提示

如果遇到错误或看不到输出,请确保指定了正确的连接字符串并加载了示例数据。

完成此步骤后,您就拥有了一个正常运行的应用程序,它使用.NET/ C#驱动程序连接到MongoDB 集群、对示例数据运行查询并打印结果。

要了解使用 .NET/C# 驱动程序连接到 Atlas 的更多信息,请参阅 Atlas 驱动程序连接指南并从 Select your language 下拉列表中选择 C#

在增删改查操作指南中了解如何使用 .NET/C# 驱动程序读取和修改数据, 或者在使用示例中了解如何执行常见操作。