通过


教程:在 Windows 应用中使用 MongoDB 数据库

本文包含从Windows应用启用使用 MongoDB 数据库所需的步骤。 另外,本文还包含一个小的代码片段,演示如何在代码中与数据库交互。

设置您的解决方案

此示例可与任何WPF、Windows Forms、WinUI 和 UWP 项目一起使用,将Windows应用连接到 MongoDB。 请按照以下步骤安装包,并试用示例代码从现有 MongoDB 数据库读取数据。

  1. 打开 包管理器控制台 (视图 -> 其他窗口 -> 包管理器控制台)。
  2. 使用命令 Install-Package MongoDB.Driver 安装 MongoDB 官方驱动程序的 NuGet 包。

这样就可以通过编程方式访问 MongoDB 数据库。

使用示例代码测试连接

以下示例代码从远程 MongoDB 客户端获取一个集合,然后向该集合添加新文档。 然后,它使用 MongoDB API 检索集合的新大小和插入的文档,并将其输出。

var client = new MongoClient("mongodb://10.xxx.xx.xxx:27017");
IMongoDatabase database = client.GetDatabase("foo");
IMongoCollection<BsonDocument> collection = database.GetCollection<BsonDocument>("bar");
var document = new BsonDocument
{
     { "name","MongoDB"},
     { "type","Database"},
     { "count",1},
     { "info",new BsonDocument { { "x", 203 }, { "y", 102 } }}
};
collection.InsertOne(document);
long count = collection.CountDocuments(document);
Console.WriteLine(count);
IFindFluent<BsonDocument, BsonDocument> document1 = collection.Find(document);
Console.WriteLine(document1.ToString());

请注意,需自定义 IP 地址和数据库名称。 端口 27017 是默认的 MongoDB 端口号。 在生产应用程序中,应将服务器地址和数据库名称等连接信息存储在应用配置中,而不是硬编码(请参阅 使用 Visual Studio Connected Services 添加Azure App Configuration)。