查找文档
您可以通过链式调用MongoCollection对象的find()和first()方法来检索集合中的一个文档。find()
方法可以传递一个查询过滤器,以在集合中查询并返回匹配过滤器的文档。如果不包含过滤器,MongoDB将返回集合中的所有文档。first()
方法返回第一个匹配的文档。
有关使用Java驱动程序查询MongoDB的更多信息,请参阅我们的查询文档指南.
您还可以将其他方法链接到find()
方法,例如sort()
,它以指定的顺序组织匹配的文档,以及projection()
,它配置返回文档中包含的字段。
有关sort()
方法的更多信息,请参阅我们的排序指南。有关projection()
方法的更多信息,请参阅我们的投影指南
find()
方法返回一个FindIterable
实例,这是一个提供多种方法来访问、组织和遍历结果的类。FindIterable
还从其父类MongoIterable
继承方法,例如first()
。
first()
方法返回检索结果中的第一个文档或null
(如果没有结果)。
示例
以下代码片段从movies
集合中找到一个文档。它使用了以下对象和方法
一个传递给
find()
方法的查询过滤器。该eq
过滤器仅匹配标题与文本'The Room'
完全匹配的电影。一个排序,它以评分降序组织匹配的文档,因此如果我们的查询匹配多个文档,则返回的文档是评分最高的文档。
一个投影,它包括
title
和imdb
字段的对象,并使用辅助方法excludeId()
排除_id
字段。
注意
此示例使用连接URI连接到MongoDB实例。有关连接到您的MongoDB实例的更多信息,请参阅连接指南。
// Retrieves a document that matches a query filter by using the Java driver package usage.examples; import static com.mongodb.client.model.Filters.eq; 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.MongoDatabase; import com.mongodb.client.model.Projections; import com.mongodb.client.model.Sorts; public class FindOne { 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"); // Creates instructions to project two document fields Bson projectionFields = Projections.fields( Projections.include("title", "imdb"), Projections.excludeId()); // Retrieves the first matching document, applying a projection and a descending sort to the results Document doc = collection.find(eq("title", "The Room")) .projection(projectionFields) .sort(Sorts.descending("imdb.rating")) .first(); // Prints a message if there are no result documents, or prints the result document as JSON if (doc == null) { System.out.println("No results found."); } else { System.out.println(doc.toJson()); } } } }
有关本页面上提到的类和方法的更多信息,请参阅以下API文档