[英]MongoDB update array element of a document by index in nodeJS
How can I increment the value of an specific element of an array of a MongoDB document in Meteor or nodeJS? 如何在Meteor或nodeJS中增加MongoDB文档数组的特定元素的值?
Say, I've following document: 说,我正在追踪文件:
{
"_id" : "4tP6ewe4Z5kwYA3Je",
"name" : "chutia",
"address" : "shonir akhra",
"itemCount" : "4",
"items" : [
"3",
"4",
"13",
"24"
]
}
I need to increment the n
'th element of items
array. 我需要增加
items
数组的第n
个元素。 Where n
is a variable. 其中
n
是变量。
The right way to do this is: 正确的方法是:
{$inc: {[`items.${idx}`]: 1}}
Where idx
is the array index. 其中
idx
是数组索引。 Courtesy MasterAM's comment 感谢MasterAM的评论
As documented here https://docs.mongodb.com/manual/reference/operator/update/inc/ , you can increment an element in an array by dot notation. 如此处https://docs.mongodb.com/manual/reference/operator/update/inc/所述 ,您可以通过点表示法增加数组中的元素。
The following example increase the first element of items by 1. 以下示例将项的第一个元素加1。
db.<collection>.update(
<query>,
{ $inc: { "items.0": 1 } }
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.