【问题标题】:MongoDB How to replace array item by indexMongoDB如何按索引替换数组项
【发布时间】:2020-02-15 07:03:59
【问题描述】:

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

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

的新评级替换一个

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

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

【问题讨论】:

  • var i = array.indexOf(5);数组[i] = 4;

标签: javascript arrays mongodb


【解决方案1】:

假设,你有一个文档

{ 
    "_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]
}

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

 { _id: editedObj.id }, // Match id. 
{ $set: { [`reviews.${index}`]: editedObj.reviews}})

【讨论】:

  • { _id: editedObj.id }, // Match id. { $set: { "reviews.index": editedObj.reviews}}); 我正在使用 node.js,当我尝试使用带有我的索引值的变量时,它给了我一个错误。知道我做错了什么吗?
  • @Goggies 我已经更新了我的代码,试试这个,让我知道这是否适合你。
  • 收到此错误Cannot create field '${index}' in element {reviews: [ "test" ]}
  • 请给我看看你的代码。
  • let updated = await Movie.updateOne( { _id: editedObj.id }, // Match id. { $set: { "reviews.${index}": editedObj.reviews}});
猜你喜欢
  • 2011-05-02
  • 1970-01-01
  • 1970-01-01
  • 2013-04-21
  • 1970-01-01
  • 2015-10-31
  • 2014-01-30
  • 2021-07-23
  • 2014-11-16
相关资源
最近更新 更多