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

查找文档

在本指南中,您可以学习;了解如何从MongoDB 数据库中检索文档。您可以使用以下方法查找文档:

以下章节将举例说明涂料店的店主如何管理客户订单。店主会追踪每笔订单的颜色和数量,在 paint_order 集合中分别对应 color 和 qty 字段:

{ "_id": 1, "color": "purple", "qty": 10 }{ "_id": 2, "color": "green", "qty": 8 }{ "_id": 3, "color": "purple", "qty": 4 }{ "_id": 4, "color": "green", "qty": 11 }

使用查找操作从MongoDB检索文档。您可以指定要检索哪些文档、以什么顺序检索文档以及要检索多少个文档。

对 MongoCollection 的实例调用 find() 方法,以过滤与所提供的查询匹配的文档。有关如何指定查询的更多信息,请参阅我们的“指定查询”指南。

然后,您可以使用 forEach() 或 cursor() 等方法来检索匹配的文档。有关更多信息,请参阅 FindIterable API文档。

要检索单个文档,可以将 first() 方法添加到 find() 调用中。要选择特定文档,可以在选择第一个文档之前使用 sort() 操作。您可能还想使用 limit() 方法来优化内存使用。有关使用排序操作时内存优化的更多信息,请参阅服务器手册。

店主想知道哪些订单包含的Paint_order 集合中的油漆多于三罐但少于九罐。

针对这种情况,涂料店老板会寻找符合标准的订单:

Bson filter = Filters.and(Filters.gt("qty", 3), Filters.lt("qty", 9)); // Retrieves documents that match the filter and prints them as JSONcollection.find(filter).forEach(doc -> System.out.println(doc.toJson()));

有关如何构建筛选器的更多信息,请参阅我们的筛选器构建器指南。

以下显示了上述查询的输出:

{ "_id": 2, "color": "green", "qty": 8 }{ "_id": 3, "color": "purple", "qty": 4 }

当所有者运行此查询后,会找到两个符合该条件的订单。

注意

设置示例

该示例使用连接 URI 连接到 MongoDB 实例。如需了解有关连接到 MongoDB 实例的更多信息,请参阅创建 MongoClient 指南。本示例还使用了Atlas 示例数据集中包含的 sample_mflix 数据库中的 movies 集合。您可以按照 MongoDB 入门指南 中的说明,将它们加载到 MongoDB Atlas 的免费集群中的数据库中。

此示例是一个完整的独立运行文件,执行以下操作:

  • 调用 find() 方法检索runtime 值小于 15 分钟的 10 文档,并对结果应用投影和排序

  • 调用 find() 和 first() 方法检索具有最高 imdb.rating(即 runtime 值小于 15 分钟)的文档,并对结果进行投影

// Retrieves documents that match a query filter by using the Java driver package org.example; import static com.mongodb.client.model.Filters.lt; import org.bson.Document;import org.bson.conversions.Bson; import com.mongodb.client.MongoClient;import com.mongodb.client.MongoClients;import com.mongodb.client.MongoCollection;import com.mongodb.client.MongoCursor;import com.mongodb.client.MongoDatabase;import com.mongodb.client.model.Projections;import com.mongodb.client.model.Sorts; import static com.mongodb.client.model.Filters.eq; public class Find { public static void main( String[] args ) { // Replace the uri string with your MongoDB deployment's connection string String uri = "<connection string uri>"; try (MongoClient mongoClient = MongoClients.create(uri)) { MongoDatabase database = mongoClient.getDatabase("sample_mflix"); MongoCollection<Document> collection = database.getCollection("movies"); // Projects "title" and "imdb" fields, excludes "_id" Bson projectionFields = Projections.fields( Projections.include("title", "imdb"), Projections.excludeId()); // Retrieves documents with a runtime of less than 15 minutes, applying the // projection and a sorting in alphabetical order FindIterable<Document> docs = collection.find(lt("runtime", 15)) .projection(projectionFields) .sort(Sorts.ascending("title")) .limit(10); // Prints the titles of the queried documents System.out.println("10 movies under 15 minutes: "); docs.forEach(doc -> System.out.println("- " + doc.get("title"))); System.out.println(); // Retrieves the document with the best imdb rating that is less // than 15 minutes long, applying the projection Document doc = collection.find(lt("runtime", 15)) .projection(projectionFields) .sort(Sorts.ascending("imdb.rating")) .first(); // Prints title of the queried document if (doc == null) { System.out.println("No results found."); } else { System.out.println("The highest rated movie under 15 minutes: " + doc.toJson().get("title")); } } }}

使用聚合操作来执行聚合管道中的各个阶段。聚合管道是产生聚合结果的多阶段转换。

要执行聚合操作,请在 MongoCollection 的实例上调用 aggregate() 方法。此方法接受聚合表达式以按顺序运行。要执行聚合,您可以定义聚合阶段来指定如何匹配文档、重命名字段和对值群组。有关更多信息,请参阅我们的聚合指南和聚合表达式操作页面。

店主想知道其paint_order 集合中哪种油漆颜色的购买量最大(销量最高)。

针对这种情况,涂料店老板创建了聚合管道,其中:

  • 匹配 paint_order 集合中的所有文档

  • 按颜色分组订单

  • 按颜色汇总数量字段

  • 将结果按数量从高到低排序

Bson filter = Filters.empty(); // Prints the collection's "color" values and each value's frequency in descending frequency ordercollection.aggregate(Arrays.asList( Aggregates.match(filter), Aggregates.group("$color", Accumulators.sum("qty", "$qty")), Aggregates.sort(Sorts.descending("qty")))) .forEach(doc -> System.out.println(doc.toJson()));

以下显示了上述聚合的输出:

{ "_id": "green", "qty": 19 }{ "_id": "purple", "qty": 14 }

涂料店老板运行聚合后,发现“绿色”是购买量最大的颜色。

有关如何构建聚合管道的更多信息,请参阅 MongoDB Server 手册页面中的聚合部分。

有关用于检索此页面上的文档的方法和类的更多信息,请参阅以下API文档: