naresh nandu
naresh nandu

Reputation: 137

Update a nested document filed and increment in mongodb

I want to update a nested document filed if present increment an old value with new value or insert a new document.

Data

New Zealand,Waikato,Hamilton,1004
New Zealand,Waikato,Auckland,145
New Zealand,Otago,Dunedin,1068

Json

{ "_id" : ObjectId("55e7d2a72f68907c17cfcb2f"), "country" : "New Zealand", 
"regions" : [ { "region" : "Waikato", "size" : 1004 }, 
{ "region" : "Waikato", "size" : 145 }, { "region" : "Otago", "size" : 1068 } ] }

In document regions array is dynamic in nature. In above document I need to update an increment field size value of ~Waikato`. Instead of putting an another record in array of regions.

My code

BasicDBObject query = new BasicDBObject();
query.put("country", "New Zealand");
query.put("regions.$.region", "Waikato");
BasicDBObject data = new BasicDBObject().append("$inc", new BasicDBObject().append("regions.$.size", 145));
BasicDBObject command = new BasicDBObject();
command.put("$set", data);
collection.update(query, command, true, false);

I need output like these:

{ "_id" : ObjectId("55e7d2a72f68907c17cfcb2f"), "country" : "New Zealand", "regions" : [ { "region" : "Waikato", "size" : 1149 }, { "region" : "Otago", "size" : 1068 } ] }

Please suggest me on these issue.

Upvotes: 1

Views: 842

Answers (1)

Blakes Seven
Blakes Seven

Reputation: 50426

Your positional $ operator only belongs in the "update portion and not the query. Also you need to .append() in the query otherwise you overwrite:

BasicDBObject query = new BasicDBObject();
query.put("country", "New Zealand");
query.append("regions.region", "Waikato");

BasicDBObject update = new BasicDBObject()
    .append("$inc", new BasicDBObject().append("regions.$.size", 145));

collection.update(query, update, true, false);

Basically looks like this ( shell wise ) :

collection.update(
    { "country": "New Zealand", "regions.region": " "Waikato" },
    { "$inc": regions.$.size": 145 },
    true,
    false
)

Upvotes: 3

Related Questions