java mongo 查询_java中mongo的条件查询
时间: 2024-01-15 09:53:14 浏览: 34
在 Java 中使用 MongoDB 进行条件查询可以使用 `com.mongodb.client.MongoCollection` 的 `find` 方法结合 `com.mongodb.client.model.Filters` 类提供的过滤条件来实现。
以下是一个简单的例子,假设我们有一个名为 `users` 的集合,其中包含了 `name` 和 `age` 两个字段:
```java
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Sorts;
import org.bson.Document;
import java.util.Arrays;
public class MongoDBExample {
public static void main(String[] args) {
// 创建 MongoDB 客户端
MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");
// 获取数据库
MongoDatabase database = mongoClient.getDatabase("test");
// 获取集合
MongoCollection<Document> collection = database.getCollection("users");
// 查询所有文档
collection.find().forEach((Consumer<Document>) document -> System.out.println(document.toJson()));
// 按条件查询文档
Document query = new Document();
query.append("age", new Document("$gte", 18)); // 年龄大于等于 18 岁
query.append("name", new Document("$in", Arrays.asList("Alice", "Bob"))); // 名字为 Alice 或 Bob
collection.find(query).forEach((Consumer<Document>) document -> System.out.println(document.toJson()));
}
}
```
上述代码中,我们使用 `Filters` 类提供的 `$gte` 和 `$in` 条件,查询年龄大于等于 18 岁且名字为 Alice 或 Bob 的文档。
更多的过滤条件可以参考 MongoDB 的官方文档:https://docs.mongodb.com/manual/reference/operator/query/
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)