java mongodb query
时间: 2023-07-08 07:34:28 浏览: 92
Mongodb java
4星 · 用户满意度95%
To query MongoDB using Java, you can use the official Java driver provided by MongoDB. Here's an example of querying a collection named "users" for documents with a field "age" greater than 25:
```java
// Create a MongoClient instance
MongoClient mongoClient = new MongoClient();
// Get a reference to the "test" database
MongoDatabase database = mongoClient.getDatabase("test");
// Get a reference to the "users" collection
MongoCollection<Document> collection = database.getCollection("users");
// Create a query to find documents with "age" greater than 25
Bson query = Filters.gt("age", 25);
// Find documents that match the query
FindIterable<Document> result = collection.find(query);
// Print the documents that match the query
for (Document document : result) {
System.out.println(document.toJson());
}
// Close the MongoClient instance
mongoClient.close();
```
This example uses the `Filters.gt()` method to create a query that matches documents with a value for "age" greater than 25. The `find()` method returns a `FindIterable` object that can be iterated over to access the matching documents. Finally, the `toJson()` method is used to print the documents in JSON format.
阅读全文