Here’s a sample code snippet that demonstrates how to read data from a MongoDB database using Java and the MongoDB Java Driver:
import com.mongodb.MongoClient; import com.mongodb.MongoClientURI; import com.mongodb.client.FindIterable; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import org.bson.Document; public class MongoDBDataReader { public static void main(String[] args) { // MongoDB connection URI String uri = "mongodb://localhost:27017"; // Database and collection names String databaseName = "mydatabase"; String collectionName = "customers"; try { // Connect to MongoDB MongoClientURI mongoURI = new MongoClientURI(uri); MongoClient mongoClient = new MongoClient(mongoURI); // Access the database MongoDatabase database = mongoClient.getDatabase(databaseName); // Access the collection MongoCollection<Document> collection = database.getCollection(collectionName); // Perform a find operation FindIterable<Document> documents = collection.find(); // Iterate over the documents for (Document document : documents) { String id = document.getObjectId("_id").toString(); String name = document.getString("name"); String email = document.getString("email"); System.out.println("ID: " + id); System.out.println("Name: " + name); System.out.println("Email: " + email); System.out.println("--------------------------"); } // Close the MongoDB client mongoClient.close(); } catch (Exception e) { e.printStackTrace(); } } }
Make sure you have the MongoDB Java Driver (such as mongodb-driver.jar
) included in your classpath. If not, you can download it from the official MongoDB website or include it as a Maven/Gradle dependency.
The code connects to the MongoDB database using the provided connection URI, accesses the specified database and collection, and performs a find operation using the find()
method on the collection. It then iterates over the resulting documents and retrieves the values of the desired fields. In this example, it assumes each document has _id
, name
, and email
fields.
Remember to handle exceptions appropriately in your production code and close the MongoDB client to release resources.