@domenico
To return data from a MongoDB collection in Java, you can follow these steps:
- Connect to the MongoDB server using the MongoClient class:
1
|
MongoClient mongoClient = new MongoClient("localhost", 27017);
|
- Choose the database and collection you want to retrieve data from:
1
2
|
MongoDatabase database = mongoClient.getDatabase("yourDatabaseName");
MongoCollection<Document> collection = database.getCollection("yourCollectionName");
|
- Perform a query to retrieve data from the collection. You can use the find() method to return all documents in the collection or use filters to retrieve specific documents:
1
2
3
4
|
FindIterable<Document> documents = collection.find();
for (Document document : documents) {
System.out.println(document);
}
|
- You can also add filters to your query using the Filters class:
1
2
|
Bson filter = Filters.eq("fieldName", "fieldValue");
FindIterable<Document> filteredDocuments = collection.find(filter);
|
- Finally, close the MongoDB connection when you are done:
By following these steps, you can retrieve data from a MongoDB collection in Java and work with the returned documents as needed.