Search code examples
javamongodbmongodb-querymongodb-java

Increment value in a subdocument in MongoDB


I have a document in my collection

{
    "_id" : ObjectId("59bd65b281a24497a0b3b401"),
    "user_id" : "1",
    "is_placed" : false,
    "items" : [ 
        {
            "product_id" : 1,
            "units" : 0
        }, 
        {
            "product_id" : 2,
            "units" : 0
        }
    ]
}

I want to increment value of 'units' for product_id = 1. Here is what my code looks like:

        MongoClient mongoConnection = new MongoClient("localhost", 27017);

    try {
        MongoDatabase db = mongoConnection.getDatabase("mydb");
        MongoCollection<Document> collection = db.getCollection("orders");
        BasicDBObject whereQuery = new BasicDBObject();
        whereQuery.put("user_id", "1");
        whereQuery.put("is_placed", false);
        whereQuery.put("product_id", 1);
        BasicDBObject incValue = new BasicDBObject("items.units", 1);
        BasicDBObject intModifier = new BasicDBObject("$inc", incValue);
        collection.updateOne(whereQuery, intModifier);
    } catch (Exception e) {
        e.printStackTrace();
    }

It does not throw any error. But neither does it increment the value. How do I achieve it? Also, is it possible to increment it only if product_id = 1 exists else put product_id = 1?


Solution

  • For updating an embedded document in an array, you should use $ operator. I cannot see you use it anywhere in your code. Your code may be, should be like this:

    MongoClient mongoConnection = new MongoClient("localhost", 27017);
    
    try {
        MongoDatabase db = mongoConnection.getDatabase("db");
        MongoCollection<Document> collection = db.getCollection("orders");
        BasicDBObject whereQuery = new BasicDBObject();
        whereQuery.put("user_id", "1");
        whereQuery.put("is_placed", false);
        whereQuery.put("items.product_id", 1);
        BasicDBObject incValue = new BasicDBObject("items.$.units", 1);
        BasicDBObject intModifier = new BasicDBObject("$inc", incValue);
        collection.updateOne(whereQuery, intModifier);
    } catch (Exception e) {
        e.printStackTrace();
    }