查找文档
Overview
在本指南中,您可以学习;了解如何从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 JSON collection.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示例数据集包含的 movies
sample_mflix
数据库中的 集合。您可以按照Atlas入门指南,将它们加载到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")); } } } }
10 movies under 15 minutes: 10 Minutes, 3x3, 7:35 in the Morning, 8, 9, A Chairy Tale, A Corner in Wheat, A Gentle Spirit, A Is for Autism, A Movie, The highest rated movie under 15 minutes: {"title": "Andrè and Wally B.", "imdb": {"rating": 5.4, "votes": 3294, "id": 86855}}
聚合操作
使用聚合操作来执行聚合管道中的各个阶段。聚合管道是产生聚合结果的多阶段转换。
要执行聚合操作,请在 MongoCollection
的实例上调用 aggregate()
方法。此方法接受聚合表达式以按顺序运行。要执行聚合,您可以定义聚合阶段来指定如何匹配文档、重命名字段和群组。有关更多信息,请参阅我们的聚合指南和聚合表达式操作页面。
例子
店主想知道其paint_order 集合中哪种油漆颜色的购买量最大(销量最高)。
针对这种情况,涂料店老板创建了聚合管道,其中:
匹配
paint_order
集合中的所有文档按颜色分组订单
按颜色汇总数量字段
将结果按数量从高到低排序
Bson filter = Filters.empty(); // Prints the collection's "color" values and each value's frequency in descending frequency order collection.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 文档
有关用于检索此页面上的文档的方法和类的更多信息,请参阅以下API文档: