Here’s a sample code snippet that demonstrates how to update data in 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 com.mongodb.client.model.Filters; import com.mongodb.client.model.UpdateOptions; import org.bson.Document; public class MongoDBDataUpdater { 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); // Update filter Document filter = new Document("name", "John Doe"); // Update document Document update = new Document("$set", new Document("email", "[email protected]")); // Update options UpdateOptions options = new UpdateOptions().upsert(true); // Perform the update collection.updateOne(filter, update, options); System.out.println("Data updated 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, defines a filter to identify the document(s) to update (in this case, based on the name field), defines an update document that specifies the field(s) to update (in this case, updating the email field), and performs the update using the updateOne()
method. The UpdateOptions
object is used to specify options for the update operation, such as upsert behavior (insert if the document doesn’t exist).
Remember to handle exceptions appropriately in your production code and close the MongoDB client to release resources.