From b541fce0a5d50a93e483970f1e9fede67ebff3ea Mon Sep 17 00:00:00 2001 From: Kapil Khandelwal Date: Fri, 25 Mar 2022 04:27:57 +0530 Subject: [PATCH] BAEL-5372: A Guide to Upsert in MongoDB (#11974) --- .../mongo/update/UpsertOperations.java | 111 ++++++++++++++++ .../mongo/update/UpsertOperationLiveTest.java | 118 ++++++++++++++++++ .../src/test/resources/vehicle.json | 3 + 3 files changed, 232 insertions(+) create mode 100644 persistence-modules/java-mongodb-2/src/main/java/com/baeldung/mongo/update/UpsertOperations.java create mode 100644 persistence-modules/java-mongodb-2/src/test/java/com/baeldung/mongo/update/UpsertOperationLiveTest.java create mode 100644 persistence-modules/java-mongodb-2/src/test/resources/vehicle.json diff --git a/persistence-modules/java-mongodb-2/src/main/java/com/baeldung/mongo/update/UpsertOperations.java b/persistence-modules/java-mongodb-2/src/main/java/com/baeldung/mongo/update/UpsertOperations.java new file mode 100644 index 0000000000..1034742225 --- /dev/null +++ b/persistence-modules/java-mongodb-2/src/main/java/com/baeldung/mongo/update/UpsertOperations.java @@ -0,0 +1,111 @@ +package com.baeldung.mongo; + +import org.bson.Document; + +import com.mongodb.MongoClient; +import com.mongodb.client.MongoCollection; +import com.mongodb.client.MongoDatabase; +import com.mongodb.client.model.Filters; +import com.mongodb.client.model.FindOneAndUpdateOptions; +import com.mongodb.client.model.ReturnDocument; +import com.mongodb.client.model.UpdateOptions; +import com.mongodb.client.model.Updates; +import com.mongodb.client.result.UpdateResult; + +public class UpsertOperations { + + private static MongoClient mongoClient; + private static MongoDatabase database; + private static MongoCollection collection; + private static String testCollectionName; + private static String databaseName; + + public static void setUp() { + + databaseName = "baeldung"; + testCollectionName = "vehicle"; + if (mongoClient == null) { + mongoClient = new MongoClient("localhost", 27017); + database = mongoClient.getDatabase(databaseName); + collection = database.getCollection(testCollectionName); + + } + + } + + public static void updateOperations() { + UpdateOptions options = new UpdateOptions().upsert(true); + UpdateResult updateResult = collection.updateOne(Filters.eq("modelName", "X5"), Updates.combine(Updates.set("companyName", "Hero Honda")), options); + System.out.println("updateResult:- " + updateResult); + + } + + public static void updateSetOnInsertOperations() { + + UpdateOptions options = new UpdateOptions().upsert(true); + UpdateResult updateSetOnInsertResult = collection.updateOne(Filters.eq("modelName", "GTPR"), + Updates.combine(Updates.set("companyName", "Hero Honda"), Updates.setOnInsert("launchYear", 2022), Updates.setOnInsert("type", "Bike"), Updates.setOnInsert("registeredNo", "EPS 5562")), options); + + System.out.println("updateSetOnInsertResult:- " + updateSetOnInsertResult); + + } + + public static void findOneAndUpdateOperations() { + + FindOneAndUpdateOptions upsertOptions = new FindOneAndUpdateOptions(); + upsertOptions.returnDocument(ReturnDocument.AFTER); + upsertOptions.upsert(true); + + Document resultDocument = collection.findOneAndUpdate(Filters.eq("modelName", "X7"), Updates.set("companyName", "Hero Honda"), upsertOptions); + System.out.println("resultDocument:- " + resultDocument); + + } + + public static void replaceOneOperations() { + + UpdateOptions options = new UpdateOptions().upsert(true); + Document replaceDocument = new Document(); + replaceDocument.append("modelName", "GTPP") + .append("companyName", "Hero Honda") + .append("launchYear", 2022) + .append("type", "Bike") + .append("registeredNo", "EPS 5562"); + UpdateResult updateReplaceResult = collection.replaceOne(Filters.eq("modelName", "GTPP"), replaceDocument, options); + + System.out.println("updateReplaceResult:- " + updateReplaceResult); + } + + public static void main(String args[]) { + + // + // Connect to cluster (default is localhost:27017) + // + setUp(); + + // + // Update with upsert operation + // + + updateOperations(); + + // + // Update with upsert operation using setOnInsert + // + + updateSetOnInsertOperations(); + + // + // Update with upsert operation using findOneAndUpdate + // + + findOneAndUpdateOperations(); + + // + // Update with upsert operation using replaceOneOperations + // + + replaceOneOperations(); + + } +} + diff --git a/persistence-modules/java-mongodb-2/src/test/java/com/baeldung/mongo/update/UpsertOperationLiveTest.java b/persistence-modules/java-mongodb-2/src/test/java/com/baeldung/mongo/update/UpsertOperationLiveTest.java new file mode 100644 index 0000000000..393d230a7b --- /dev/null +++ b/persistence-modules/java-mongodb-2/src/test/java/com/baeldung/mongo/update/UpsertOperationLiveTest.java @@ -0,0 +1,118 @@ +package com.baeldung.mongo; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.List; + +import org.bson.Document; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + +import com.mongodb.MongoClient; +import com.mongodb.client.MongoCollection; +import com.mongodb.client.MongoDatabase; +import com.mongodb.client.model.DeleteOneModel; +import com.mongodb.client.model.Filters; +import com.mongodb.client.model.FindOneAndUpdateOptions; +import com.mongodb.client.model.InsertOneModel; +import com.mongodb.client.model.ReplaceOneModel; +import com.mongodb.client.model.ReturnDocument; +import com.mongodb.client.model.UpdateManyModel; +import com.mongodb.client.model.UpdateOneModel; +import com.mongodb.client.model.UpdateOptions; +import com.mongodb.client.model.Updates; +import com.mongodb.client.model.WriteModel; +import com.mongodb.client.result.UpdateResult; + +public class UpsertOperationLiveTest { + + private static MongoClient mongoClient; + private static MongoDatabase db; + private static MongoCollection collection; + private static final String DATASET_JSON = "/vehicle.json"; + + @BeforeClass + public static void setup() throws IOException { + if (mongoClient == null) { + mongoClient = new MongoClient("localhost", 27017); + db = mongoClient.getDatabase("baeldung"); + collection = db.getCollection("vehicle"); + collection.drop(); + + InputStream is = BulkOperationLiveTest.class.getResourceAsStream(DATASET_JSON); + BufferedReader reader = new BufferedReader(new InputStreamReader(is)); + reader.lines() + .forEach(line -> collection.insertOne(Document.parse(line))); + reader.close(); + } + } + + @Test + public void givenVehicleCollection_whenupdateOperations_thenCheckingForDocument() { + UpdateOptions options = new UpdateOptions().upsert(true); + UpdateResult updateResult = collection.updateOne(Filters.eq("modelName", "X5"), Updates.combine(Updates.set("companyName", "Hero Honda")), options); + Document vehicleDetail = collection.find(Filters.eq("modelName", "X5")) + .first(); + assertNotNull(vehicleDetail); + assertFalse(vehicleDetail.isEmpty()); + + } + + @Test + public void givenVehicleCollection_whenupdateSetOnInsertOperations_thenCheckingForDocument() { + + UpdateOptions options = new UpdateOptions().upsert(true); + UpdateResult updateSetOnInsertResult = collection.updateOne(Filters.eq("modelName", "GTPR"), + Updates.combine(Updates.set("companyName", "Hero Honda"), Updates.setOnInsert("launchYear", 2022), Updates.setOnInsert("type", "Bike"), Updates.setOnInsert("registeredNo", "EPS 5562")), options); + + Document vehicleDetail = collection.find(Filters.eq("modelName", "GTPR")) + .first(); + assertNotNull(vehicleDetail); + assertFalse(vehicleDetail.isEmpty()); + } + + @Test + public void givenVehicleCollection_whenfindOneAndUpdateOperations_thenCheckingForDocument() { + + FindOneAndUpdateOptions upsertOptions = new FindOneAndUpdateOptions(); + upsertOptions.returnDocument(ReturnDocument.AFTER); + upsertOptions.upsert(true); + + Document resultDocument = collection.findOneAndUpdate(Filters.eq("modelName", "X7"), Updates.set("companyName", "Hero Honda1"), upsertOptions); + Document vehicleDetail = collection.find(Filters.eq("modelName", "X7")) + .first(); + assertNotNull(vehicleDetail); + assertFalse(vehicleDetail.isEmpty()); + } + + @Test + public void givenVehicleCollection_whenreplaceOneOperations_thenCheckingForDocument() { + + UpdateOptions options = new UpdateOptions().upsert(true); + Document replaceDocument = new Document(); + replaceDocument.append("modelName", "GTPP") + .append("companyName", "Hero Honda") + .append("launchYear", 2022) + .append("type", "Bike") + .append("registeredNo", "EPS 5562"); + UpdateResult updateReplaceResult = collection.replaceOne(Filters.eq("modelName", "GTPP"), replaceDocument, options); + + Document vehicleDetail = collection.find(Filters.eq("modelName", "GTPP")) + .first(); + assertNotNull(vehicleDetail); + assertFalse(vehicleDetail.isEmpty()); + } + + @AfterClass + public static void cleanUp() { + mongoClient.close(); + } +} + diff --git a/persistence-modules/java-mongodb-2/src/test/resources/vehicle.json b/persistence-modules/java-mongodb-2/src/test/resources/vehicle.json new file mode 100644 index 0000000000..3dc71b911b --- /dev/null +++ b/persistence-modules/java-mongodb-2/src/test/resources/vehicle.json @@ -0,0 +1,3 @@ +{ "companyName":"Nissan", "modelName":"GTR", "launchYear":2016,"type":"Sports", "registeredNo":"EPS 5561" } +{ "companyName":"BMW", "modelName":"X5", "launchYear":2020, "type":"SUV", "registeredNo":"LLS 6899" } +{ "companyName":"Honda", "modelName":"Gold Wing", "launchYear":2018, "type":"Bike", "registeredNo":"LKS 2477"}