0

Here's a simplified example of the document

{  
   "username":"someUsername",
   "bank":[  
      {  
         "item_id":45,
         "item_amount":10
      },
      {  
         "item_id":45,
         "item_amount":10
      }
   ]
}

How can I increment item_id=45's item_amount value by say 3? And do it in a way where if item_id=45 doesn't exist in the array it will get added and it's item_amount value will be 3.

I believe MongoCollection's updateOne is the newest way to work with mongodb with java. I'd prefer to use that method, I just can't figure out the proper way to do it. (I've found plenty of answers using the old update method, so please don't reference those unless I'm missing something useful from them).

CamHart
  • 3,825
  • 7
  • 33
  • 69

1 Answers1

0

Please try with following snippet;0

db.items.find({'bank.item_id': 45}).forEach(function(myDoc) {
    var count_action = {};
    if (is_itemid_exist(45,myDoc.bank,'item_id')) {
        count_action['bank.$.item_amount'] =3; 
        db.items.update(
        {'bank.item_id': 45},
        {
            $inc: count_action 
        });
    } else {
        db.items.insert({'bank': [{'item_id':45,' item_amount':3}]})
    }
});

function is_itemid_exist which is used in above query -

function is_itemid_exist(value, search,key) {
        if (!search || (search.constructor !== Array && search.constructor !== Object)) {
            return false;
        }
        for (var i = 0; i < search.length; i++) {
            if (search[i].key === value) {
                return true;
            }
        }
        return false;
    }

Thanks

Dineshaws
  • 2,065
  • 16
  • 26
  • 1
    This looks like javascript code to me. I need java. – CamHart Apr 17 '15 at 07:49
  • query has syntax as mongodb and you can update function 'is_itemid_exist' as per your use – Dineshaws Apr 17 '15 at 07:51
  • By query do you mean QueryBuilder? Because I'm not seeing a Query class in mongodb's 3.0 java driver api. But maybe I'm blind? https://api.mongodb.org/java/current/ – CamHart Apr 17 '15 at 08:38