-
-
Save couragecowardlydog/34e8026bd74b69031b198f5e25b4adfe to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package io.gitrebase; | |
import com.mongodb.client.MongoClient; | |
import com.mongodb.client.MongoClients; | |
import com.mongodb.client.MongoCollection; | |
import com.mongodb.client.MongoDatabase; | |
import com.mongodb.client.model.Filters; | |
import com.mongodb.client.result.UpdateResult; | |
import org.bson.Document; | |
import java.util.concurrent.ExecutorService; | |
import java.util.concurrent.Executors; | |
public class InventoryUpdate { | |
private static final String DATABASE_NAME = "test"; | |
private static final String COLLECTION_NAME = "inventory"; | |
public static void main(String[] args) { | |
MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017,localhost:27018,localhost:27019/?replicaSet=rs0"); | |
MongoDatabase database = mongoClient.getDatabase(DATABASE_NAME); | |
MongoCollection<Document> collection = database.getCollection(COLLECTION_NAME); | |
Document product = new Document("productCode", "PROD_001") | |
.append("name", "Laptop") | |
.append("quantity", 50); | |
collection.insertOne(product); | |
System.out.println("Product created: " + product.toJson()); | |
ExecutorService executorService = Executors.newFixedThreadPool(2); | |
executorService.submit(() -> updateProductQuantity(collection, "PROD_001", -5)); // decrease by 5 | |
executorService.submit(() -> updateProductQuantity(collection, "PROD_001", 10)); // increase by 10 | |
executorService.shutdown(); | |
} | |
public static void updateProductQuantity(MongoCollection<Document> collection, String productCode, int quantityChange) { | |
try { | |
// Find product by productCode | |
Document productDoc = collection.find(Filters.eq("productCode", productCode)).first(); | |
if (productDoc != null) { | |
int currentQuantity = productDoc.getInteger("quantity"); | |
int updatedQuantity = currentQuantity + quantityChange; | |
Document updatedDoc = new Document("quantity", updatedQuantity); | |
UpdateResult result = collection.updateOne( | |
Filters.eq("productCode", productCode), | |
new Document("$set", updatedDoc) | |
); | |
System.out.println("Updated product " + productCode + ": quantity changed by " + quantityChange + | |
" | New Quantity: " + updatedQuantity); | |
} else { | |
System.out.println("Product not found for code: " + productCode); | |
} | |
} catch (Exception e) { | |
System.out.println("Error during update: " + e.getMessage()); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment