For the document matching the criteria _id equal to 100, the following operation update the value second element (array index of 1) in the tags field and the rating field in the first element (array index of 0) of the ratings array.
db.products.update(
{ _id: 100 },
{ $set:
{
"tags.1": "rain gear",
"ratings.0.rating": 2
}
}
)
以上引用自mongodb $set documentation ,我将如何为索引添加一个变量,而不是 "tags.1"
它变成"tags."+index
例如,如果 index
等于 7 它将返回相当于 "tags.7"
.
这是我的代码:
Users.findOneAndUpdate({'username': post.username}, {
$set: {
"notifications.0": {
'id': post._id, 'message': post.message, 'amount': amount
}
}
}, function () {})
它工作得很好,但只是因为我硬编码了 0
作为索引。我想替换那个硬编码的 0
与 index
变量。
最佳答案
像这样构建查询
var key = "notifications."+index;
var obj = {};
obj[key] = { 'id': post._id, 'message': post.message, 'amount': amount };
Users.findOneAndUpdate({'username': post.username}, { $set: obj }, function () {}
关于javascript - 使用带有索引变量的 $set 来更新文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43711967/