Here’s a sample code snippet that demonstrates how to write data to a MongoDB database using Java and the MongoDB Java Driver:
import com.mongodb.MongoClient; import com.mongodb.MongoClientURI; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import org.bson.Document; public class MongoDBDataWriter { 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); // Create a new document Document document = new Document(); document.append("name", "John Doe"); document.append("email", "[email protected]"); // Insert the document into the collection collection.insertOne(document); System.out.println("Data inserted successfully!"); // 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, creates a new Document
object representing the data to be inserted, and inserts it into the collection using the insertOne()
method. In this example, the document contains name
and email
fields.
Remember to handle exceptions appropriately in your production code and close the MongoDB client to release resources.
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, creates a new Document
object representing the data to be inserted, and inserts it into the collection using the insertOne()
method. In this example, the document contains name
and email
fields.
Remember to handle exceptions appropriately in your production code and close the MongoDB client to release resources.