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

Retrieve Data

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

提示

互动实验室

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

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

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

本页的示例使用以下 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

获取或设置查询结果中返回的每个批处理中的最大文档数量。如果未设置 batchSize,则 Find() 方法的初始批处理大小为 101 个文档,后续批处理的最大大小为 16 MiB。此选项可以强制执行比 16 MiB 更小的限制,但不能执行更大的限制。如果将 batchSize 设置为导致批处理大于 16 MiB 的限制,则此选项无效,Find() 方法使用默认批处理大小。

Collation

Sets the collation options. See the Collation section of this page for more information.

Comment

将注释设置为查询,以便查看分析器日志。

Hint

设置要使用的索引提示。

MaxTime

设置此操作在服务器上的最长执行时间。

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

要为操作配置排序规则,请创建 Collation 类的实例。

下表描述了 Collation 构造函数接受的参数。它还列出了相应的类属性,您可以使用这些属性读取每个设置的值。

Parameter
说明
类属性

locale

Specifies the International Components for Unicode (ICU) locale. For a list of supported locales, see Collation Locales and Default Parameters in the MongoDB Server Manual.

If you want to use simple binary comparison, use the Collation.Simple static property to return a Collation object with the locale set to "simple".
Data Type: string

Locale

caseLevel

(可选)指定是否包含大小写比较。

当此参数为 true 时,驱动程序的行为取决于 strength 参数的值:

- 如果 strengthCollationStrength.Primary,则驱动程序会比较基本字符和大小写。
- 如果 strengthCollationStrength.Secondary,则驱动程序会比较基本字符、变音符、其他次要差异和大小写。
- 如果 strength 为任何其他值,则会忽略此参数。

当此参数为 false 时,驱动程序不会在强度级别 PrimarySecondary 包含大小写比较。

数据类型boolean
默认值false

CaseLevel

caseFirst

(Optional) Specifies the sort order of case differences during tertiary level comparisons.

Data Type: CollationCaseFirst
Default: CollationCaseFirst.Off

CaseFirst

strength

(Optional) Specifies the level of comparison to perform, as defined in the ICU documentation.

Data Type: CollationStrength
Default: CollationStrength.Tertiary

Strength

numericOrdering

(可选)指定驾驶员是否将数字字符串作为数字进行比较。如果此参数为

true10210210

false102,则驾驶员将数字字符串作为数字进行比较。示例,在比较字符串1 2102"" 和和“”,则驾驶员会将这些值视为 和 ,并发现 更大。如果此参数为 或已排除,则驾驶员会将数字字符串作为字符串进行比较。示例,在比较字符串 ""

和和“”,驾驶员一次比较一个字符。因为""小于“”,则驾驶员会找到“”小于“”。有关更多信息,请参阅MongoDB Server手册中的排序规则限制。数据类型:

boolean
默认值:false

NumericOrdering

alternate

(Optional) Specifies whether the driver considers whitespace and punctuation as base characters for purposes of comparison.

Data Type: CollationAlternate
Default: CollationAlternate.NonIgnorable (spaces and punctuation are considered base characters)

Alternate

maxVariable

(Optional) Specifies which characters the driver considers ignorable when the alternate argument is CollationAlternate.Shifted.

Data Type: CollationMaxVariable
Default: CollationMaxVariable.Punctuation (the driver ignores punctuation and spaces)

MaxVariable

normalization

(Optional) Specifies whether the driver normalizes text as needed.

Most text doesn't require normalization. For more information about normalization, see the ICU documentation.

Data Type: boolean
Default: false

Normalization

backwards

(可选)指定包含变音符号的字符串是否从字符串的后部到前部排序。

数据类型boolean
默认false

Backwards

有关排序规则的更多信息,请参阅MongoDB Server手册中的排序规则页面。

此示例将执行以下动作:

  • 查找 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
...

提示

清理

Create a cursor with a using statement to automatically invoke the Dispose() method once the cursor is no longer in use.

要学习;了解有关查询筛选器的更多信息,请参阅创建查询筛选器。

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

有关查找操作的可运行示例,请参阅以下用法示例:

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