1

私の mongoDB ドキュメントは次のようになります。

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

ユーザーの要求に応じて、「threeOne」または「threeTwo」のいずれかをインクリメントしたいと考えています。

これまでの私のコード:

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) {

});

???? 次のようになります。{$inc: {valThree: {whichFieldToUpdate : 1 } }

4

1 に答える 1

2
var field = 'valThree.' + request.body.field;
var inc =  {};
inc[field] = 1;

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

});
于 2013-12-18T18:02:53.527 に答える