1

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.

Nilesh Thakkar
  • 1,442
  • 4
  • 25
  • 36
naresh nandu
  • 137
  • 2
  • 10
  • 1
    possible duplicate of [MongoDB - Update an object in nested Array](http://stackoverflow.com/questions/10522347/mongodb-update-an-object-in-nested-array) – Neo-coder Sep 03 '15 at 05:21

1 Answers1

3

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
)
Blakes Seven
  • 49,422
  • 14
  • 129
  • 135