MongoDB increment number in subdocument

1.9k views Asked by At

My mongoDB document looks like this:

   {
      valOne: "one",
      valTwo: "two",
      valThree: {
                  threeOne: 0,
                  threeTwo: 0
                }
    }

i would like to increment either "threeOne" or "threeTwo" depending on the user request.

My code so far:

var whichFieldToUpdate = request.body.field; //can be either threeOne or threeTwo
var id = new BSON.ObjectID(request.body.id); //contains document id

db.collection('name').update({_id: id}, {$inc: { ?????? } },
  function(err, result) {

});

???? should be something like this: {$inc: {valThree: {whichFieldToUpdate : 1 } }

1

There are 1 answers

0
Will Shaver On BEST ANSWER
var field = 'valThree.' + request.body.field;
var inc =  {};
inc[field] = 1;

db.collection('name').update({_id: id}, {$inc: inc } },
  function(err, result) {

});