java如何查询mongodb
查询 MongoDB 的 Java 方法
在 Java 中查询 MongoDB 需要使用 MongoDB 的 Java 驱动程序。以下是几种常见的查询方式。
连接 MongoDB 数据库
确保已经添加 MongoDB Java 驱动的依赖(如 Maven 的 mongodb-driver-sync)。连接数据库的代码如下:
MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");
MongoDatabase database = mongoClient.getDatabase("testDB");
MongoCollection<Document> collection = database.getCollection("testCollection");
查询所有文档
使用 find() 方法查询集合中的所有文档:
FindIterable<Document> documents = collection.find();
for (Document doc : documents) {
System.out.println(doc.toJson());
}
条件查询
通过 Filters 类构造查询条件,例如查询 name 字段为 "John" 的文档:

Document query = new Document("name", "John");
FindIterable<Document> result = collection.find(query);
// 或使用 Filters 类
Bson filter = Filters.eq("name", "John");
FindIterable<Document> result = collection.find(filter);
范围查询
查询 age 大于 25 的文档:
Bson filter = Filters.gt("age", 25);
FindIterable<Document> result = collection.find(filter);
多条件组合查询
使用 and 或 or 组合多个条件:

Bson filter = Filters.and(
Filters.eq("name", "John"),
Filters.gt("age", 25)
);
FindIterable<Document> result = collection.find(filter);
投影查询(返回指定字段)
通过 projection 指定返回的字段:
Bson projection = Projections.fields(
Projections.include("name", "age"),
Projections.excludeId()
);
FindIterable<Document> result = collection.find().projection(projection);
排序和分页
使用 sort 和 limit 进行排序和分页:
Bson sort = Sorts.descending("age");
FindIterable<Document> result = collection.find()
.sort(sort)
.limit(10);
聚合查询
使用 aggregate 进行复杂的聚合操作:
List<Bson> pipeline = Arrays.asList(
Aggregates.match(Filters.gt("age", 20)),
Aggregates.group("$name", Accumulators.sum("totalAge", "$age"))
);
MongoIterable<Document> result = collection.aggregate(pipeline);
注意事项
- 确保 MongoDB 服务正在运行,并且 Java 驱动版本与 MongoDB 版本兼容。
- 查询结果可以通过
FindIterable遍历或转换为列表(如result.into(new ArrayList<>()))。 - 对于大型数据集,使用分页或游标避免内存问题。
通过以上方法,可以灵活地在 Java 中查询 MongoDB 数据。






