how to query data using mongo in java
时间: 2024-02-20 19:56:31 浏览: 23
To query data using MongoDB in Java, you can use the following steps:
1. Create a MongoClient instance to connect to the MongoDB server.
```
MongoClient mongoClient = new MongoClient("localhost", 27017);
```
2. Get a reference to the database you want to query.
```
MongoDatabase database = mongoClient.getDatabase("mydb");
```
3. Get a reference to the collection you want to query.
```
MongoCollection<Document> collection = database.getCollection("mycollection");
```
4. Build a query using the QueryBuilder class.
```
QueryBuilder queryBuilder = QueryBuilder.start("name").is("John");
```
5. Execute the query on the collection.
```
FindIterable<Document> result = collection.find(queryBuilder.get());
```
6. Iterate over the result set to retrieve the data.
```
for (Document doc : result) {
System.out.println(doc.toJson());
}
```
Note: This code requires the MongoDB Java driver to be installed in your project.