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 回答