Docs 菜单
Docs 主页
/ / /
Java (Sync) 驱动程序
/ /

查找多个文档

您可以通过调用 MongoCollection 对象的 find() 方法来查询集合中的多个文档。将查询筛选器传递给 find() 方法进行查询并返回集合中与筛选器匹配的文档。如果不包含过滤器,MongoDB 将返回集合中的所有文档。

有关使用 Java 驱动程序查询 MongoDB 的更多信息,请参阅有关查询文档指南。

您还可以将方法链式调用至 find() 方法,例如以指定顺序组织匹配文档的 sort(),以及配置返回文档中包含的字段的 projection()

有关sort()方法的更多信息,请参阅我们的排序指南。 有关projection()方法的更多信息,请参阅我们的投影指南

find() 方法返回 FindIterable 类的一个实例,这个类提供访问、组织和遍历结果的多种方法。FindIterable 还从其父类 MongoIterable 继承方法,该父类实施核心 Java 接口 Iterable

您可以对 MongoIterable 调用 iterator() 方法,返回一个可用于遍历结果的 MongoCursor 实例。您可以对 MongoCursor 调用方法,例如调用 hasNext() 来检查是否存在其他结果或者调用 next() 返回集合中的下一份文档。如果没有文档与查询匹配,则调用 hasNext() 将返回 false,因此调用 next() 会抛出异常。

如果您在迭代器返回最终结果后或不存在结果时对迭代器调用next(),则会引发java.util.NoSuchElementException类型的异常。在调用next()之前,请始终使用hasNext()检查是否存在其他结果。

下面的代码段查找并打印了与 movies 集合上的查询匹配的所有文档。它使用以下对象和方法:

  • 传递给 find() 方法的查询筛选器lt() 筛选器只匹配运行时少于 15 分钟的电影。

  • 按标题降序对返回文档进行组织的排序(“Z”在“A”之前)。

  • 使用辅助方法 excludeId() 包含 titleimdb 字段中的对象并排除 _id 字段的投影

注意

该示例使用连接 URI 连接到 MongoDB 实例。如需了解有关连接到 MongoDB 实例的更多信息,请参阅连接指南

// Retrieves documents that match a query filter by using the Java driver
package usage.examples;
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;
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");
// Creates instructions to project two document fields
Bson projectionFields = Projections.fields(
Projections.include("title", "imdb"),
Projections.excludeId());
// Retrieves documents that match the filter, applying a projection and a descending sort to the results
MongoCursor<Document> cursor = collection.find(lt("runtime", 15))
.projection(projectionFields)
.sort(Sorts.descending("title")).iterator();
// Prints the results of the find operation as JSON
try {
while(cursor.hasNext()) {
System.out.println(cursor.next().toJson());
}
} finally {
cursor.close();
}
}
}
}

提示

Legacy API

如果您使用的是传统 API,请参阅我们的常见问题页面,了解需要对该代码示例进行哪些更改。

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

  • FindIterable

  • MongoIterable

  • MongoCursor

  • find()

后退

查找文档