2

如何使用MongoDB替换数组中特定索引处的值?

假设一个电影评论集合有一个带有单独数字的评级数组,我想用仅使用索引的新评级替换一个

让数组 = [1, 5, 3, 7]

如何将 5 替换为 4?再次只使用索引

4

1 回答 1

2

假设,你有一个文件

{ 
    "_id" : 1, 
    "array" :  [1, 5, 3, 7]
}

然后,您可以使用点运算符更新特定索引处的数组值, 即array.<index> 使用$set运算符

db.collection.update(
  { /*match query*/ },
  { $set: { "array.1": 4 } }  // array.index where index=0,1,2,...
)

更新后的文档变为,

{ 
    "_id" : 1, 
    "array" :  [1, 4, 3, 7]
}

您需要连接键中的索引。尝试这个

 { _id: editedObj.id }, // Match id. 
{ $set: { [`reviews.${index}`]: editedObj.reviews}})
于 2020-02-15T07:36:21.003 回答