首页 > 解决方案 > 如何更新数组中的特定对象?

问题描述

我在 MongoDB 中有一个如下所示的数据

{
_id: aasdfeasfeasdf,
todo: [
         {_todoIde: 333, _with: []},
         {_todoIde: 111, _with: []},
      ]
}

我要$addToSet重视_todoIde: 333_with喜欢{_todoIde: 333, _with: [aaaa]},。我该怎么做?

.updateOne(
   {_id},
   { $addToSet: {}}
)

我找到了该文档,但我无法指定_todoIde: 333仅更新该文档。

标签: node.jsmongoose

解决方案


位置$运算符标识要更新的数组中的元素,而无需明确指定该元素在数组中的位置,

.updateOne(
  { _id: "aasdfeasfeasdf", "todo._todoIde": 333 },
  {
    $addToSet: {
      "todo.$._with": "aaaa"
    }
  }
)

操场


推荐阅读