文档菜单
文档首页
/ / /
Java 同步驱动程序
/ /

查找多个文档

您可以通过调用find() 方法用于在 MongoCollection 对象上。将查询过滤器传递给 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" 之前)。

  • 一个包含 titleimdb 字段的 投影,并使用辅助方法 excludeId() 排除 _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();
}
}
}
}

提示

旧版 API

如果您正在使用旧版 API,请参阅我们的常见问题解答页面,了解您需要对此代码示例进行哪些更改。

有关本页上提到的类和方法的更多信息,请参阅以下 API 文档

  • FindIterable

  • MongoIterable

  • MongoCursor

  • find()

返回上一页

查找单个