Docs 菜单
Docs 主页
/ / /
C#/ .NET驱动程序
/ / /

Retrieve Data

通过本指南,您可以了解如何使用 MongoDB .NET/C# 驱动程序通过读取操作从 MongoDB 集合中检索数据。您可以调用 Find() 方法来检索与一组条件匹配的文档。

提示

互动实验室

本页包括一个简短的交互式实验,演示如何使用 Find() 方法检索数据。您无需安装 MongoDB 或代码编辑器,即可直接在浏览器窗口中完成此实验。

若要启动实验室,请单击页面顶部的“Open Interactive Tutorial”按钮。要将实验室扩展为全屏格式,请单击实验室窗格右上角的全屏按钮 ()。

本指南中的示例使用 Atlas示例数据集中sample_restaurants.restaurants集合。 要学习;了解如何创建免费的MongoDB Atlas 群集并加载示例数据集,请参阅快速入门。

本页的示例使用以下 RestaurantAddressGradeEntry 类作为模型:

public class Restaurant
{
public ObjectId Id { get; set; }
public string Name { get; set; }
[BsonElement("restaurant_id")]
public string RestaurantId { get; set; }
public string Cuisine { get; set; }
public Address Address { get; set; }
public string Borough { get; set; }
public List<GradeEntry> Grades { get; set; }
}
public class Address
{
public string Building { get; set; }
[BsonElement("coord")]
public double[] Coordinates { get; set; }
public string Street { get; set; }
[BsonElement("zipcode")]
public string ZipCode { get; set; }
}
public class GradeEntry
{
public DateTime Date { get; set; }
public string Grade { get; set; }
public float? Score { get; set; }
}

注意

restaurants集合中的文档使用蛇形命名规则。本指南中的示例使用 ConventionPack 将集合中的字段反序列化为 Pascal 语句,并将它们映射到 Restaurant 类中的属性。

如需了解有关自定义序列化的更多信息,请参阅“自定义序列化”。

使用 Find() 方法从集合检索文档。Find() 方法会使用查询筛选器并返回所有匹配的文档。查询筛选器是一个对象,它可用于指定要在查询中检索的文档。

如需了解有关查询过滤器的更多信息,请参阅指定查询

要查找集合中的单个文档,请传递查询筛选器,其中指定要查找的文档条件,然后链接 FirstOrDefault()FirstOrDefaultAsync() 方法。如有多个文档与查询筛选器匹配,则这些方法将从检索到的结果中返回第一个匹配的文档。如果没有文档与查询筛选器匹配,则这些方法返回 null

var restaurants = _restaurantsCollection.Find(filter).FirstOrDefault();
var restaurants = await _restaurantsCollection.Find(filter).FirstOrDefaultAsync();

提示

第一个文档

如果未指定排序条件,FirstOrDefault() 方法将按自然顺序返回磁盘上的第一份文档。

如要查看使用 Find() 方法查找单个文档的完整示例,请参阅更多信息

要查找集合中的多个文档,请将查询筛选器传递给 Find() 方法,其中指定要检索的文档条件。

您可以使用游标迭代 Find() 方法返回的文档。游标机制允许应用程序迭代数据库结果,同时在给定时间仅将数据库结果的子集保留在内存中。当 Find() 方法返回大量文档时,游标非常有用。

要使用游标迭代文档,请将查询筛选器传递给指定待查找文档条件的 Find() 方法,然后链式调用 ToCursor()ToCursorAsync() 方法。若要查看同步或异步示例,请选择相应的标签页。

var restaurants = _restaurantsCollection.Find(filter).ToCursor();
var restaurants = await _restaurantsCollection.Find(filter).ToCursorAsync();

如果您要返回少量文档,或者需要将结果作为 List 对象返回,使用 ToList()ToListAsync() 方法。

要查找集合中的多个文档并将它们作为列表保存在内存中,将查询筛选器传递给指定要查找的文档标准的 Find() 方法,然后链接 ToList()ToListAsync() 方法。若要查看同步或异步示例,请选择相应的标签页。

var restaurants = _restaurantsCollection.Find(filter).ToList();
var restaurants = await _restaurantsCollection.Find(filter).ToListAsync();

要查看使用 Find() 方法查找多个文档的完整示例,请参阅更多信息

注意

查找所有文档

要查找集合中的所有文档,请将空筛选器传递给 Find() 方法。

var filter = Builders<Restaurant>.Filter.Empty;
var allRestaurants = _restaurantsCollection.Find(filter);

要查看利用 Find() 方法查找所有文档的完整可运行示例,请参阅更多信息

你可以通过传递 FindOptions 对象来修改 Find() 方法的行为。

可以使用以下方法配置常用选项:

方法
说明

BatchSize

Gets or sets the maximum number of documents within each batch returned in a query result. If batchSize is not set, the Find() method has an initial batch size of 101 documents and a maximum size of 16 mebibytes (MiB) for each subsequent batch. This option can enforce a smaller limit than 16 MiB, but not a larger one. If you set batchSize to a limit that results in batches larger than 16 MiB, this option has no effect and the Find() method uses the default batch size.

Collation

Sets the collation options.

Comment

Sets the comment to the query to make looking in the profiler logs easier.

Hint

Sets the hint for which index to use.

MaxTime

Sets the maximum execution time on the server for this operation.

要查看可用选项的完整列表,请参阅 FindOptions 属性

此示例将执行以下动作:

  • 查找 cuisine 字段中包含“Pizza”的所有文档

  • BatchSize 设置为 3

  • 将结果存储在游标中

  • 打印游标引用的文档

var filter = Builders<Restaurant>.Filter.Eq("cuisine", "Pizza");
var findOptions = new FindOptions { BatchSize = 3 };
using (var cursor = _restaurantsCollection.Find(filter, findOptions).ToCursor())
{
foreach (var r in cursor.ToEnumerable())
{
WriteLine(r.Name);
}
}
Pizza Town
Victoria Pizza
...

提示

清理

使用 using 语句创建游标,以便在不再使用游标时自动调用 Dispose() 方法。

如需了解有关查询过滤器的更多信息,请参阅指定查询

若要学习;了解如何使用 LINQ 指定查询,请参阅聚合操作的 LINQ事务语法。

要查看 Find() 方法的可运行示例,请参阅查找文档页面。

要进一步了解本指南所讨论的任何方法或类型,请参阅以下 API 文档:

后退

读取

在此页面上

  • Overview
  • 样本数据
  • 查找文档
  • 查找一个文档
  • 查找多个文档
  • 修改查找行为
  • 例子
  • 更多信息
  • API 文档