我的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 } }
答案 0 :(得分:1)
var field = 'valThree.' + request.body.field;
var inc = {};
inc[field] = 1;
db.collection('name').update({_id: id}, {$inc: inc } },
function(err, result) {
});