[英]update array in mongoDB document by variable index
How can I update an array in a mongoDB document by index, which is stored in a variable? 如何通过索引更新mongoDB文档中的数组,该数据存储在变量中?
{
_id: 'IDString',
field: [ bla, bla, old, bla ];
}
let i = 2;
Collection.update(
{ _id: 'IDString' },
{ $set:
{ 'field.$.i': 'new' }
}
);
So the result should be: 所以结果应该是:
{
_id: 'IDString',
field: [ bla, bla, new, bla ];
}
My code wouldn't work, as I want to use the variable i
. 我的代码不起作用,因为我想使用变量
i
。
Use the dot notation syntax to set up your update document since this will access an element of an array by the zero-based index position. 使用点表示法语法设置更新文档,因为这将通过从零开始的索引位置访问数组的元素。 You would have to concatenate the array name with the dot (.) and zero-based index position, and enclose in quotes.
您必须将数组名称与点(。)和从零开始的索引位置连接起来,并用引号括起来。
So in your example, you would need to set up the update document dynamically to produce 因此,在您的示例中,您需要动态设置更新文档以进行生成
var update = { "$set": { "field.2": "new" } }
The following code snippet shows this: 以下代码段显示了这一点:
var i = 2,
update = { "$set": {} };
update["$set"]["field."+i] = "new";
db.collection.update({ "_id": "IDString" }, update)
Collection.update(
{ _id: 'IDString', field.2 : 1 },
{ $set: {
"field.$" : "new" }
}
)
This should work, if not - comment below 这应该有用,如果没有 - 请在下面评论
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.