How to return data from mongodb collection in java?

Member

by domenico , in category: MySQL , a month ago

How to return data from mongodb collection in java?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by ryleigh , a month ago

@domenico 

To return data from a MongoDB collection in Java, you can follow these steps:

  1. Connect to the MongoDB server using the MongoClient class:
1
MongoClient mongoClient = new MongoClient("localhost", 27017);


  1. Choose the database and collection you want to retrieve data from:
1
2
MongoDatabase database = mongoClient.getDatabase("yourDatabaseName");
MongoCollection<Document> collection = database.getCollection("yourCollectionName");


  1. 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);
}


  1. 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);


  1. Finally, close the MongoDB connection when you are done:
1
mongoClient.close();


By following these steps, you can retrieve data from a MongoDB collection in Java and work with the returned documents as needed.