MongoDB -如何使用管道样式的数组过滤器进行更新

mbzjlibv  于 2023-02-11  发布在  Go
关注(0)|答案(1)|浏览(175)

我使用Mongo 4.4,并尝试使用updateOne更新嵌套数组元素来执行聚合管道更新。为了更新特定的数组成员,我在选项中使用了arrayFilter,但由于某些原因,我收到了错误消息:
不能为管道样式更新指定arrayFilters。
查询如下所示:

updateOne(
{ _id: <some_id>},
[
  {
    $set: { 'arr.$[element]': <new_value> }
  },
  {
    $set: { somefield: { '$cond': { <the condition content> } } }
  }
],
{
  arrayFilters: [ {'element.id': <new_value>.id } ]
}
);

怎么解决呢?
编辑1:
文档的示例如下:

{
  _id: 932842242342354234,
  lastUpdateTime: <old time>,
  comments: [
    {
      id: 390430,
      content: "original",
      lastUpdated: <sime time>
    }
  ],
}

我想要做的查询是更新一个注解,并且只有当内容lastUpdated的时间晚于当前文档的当前lastEditTime时,才同时更新主对象的字段lastEditTime

updateOne(
{ _id: documentId},
[
  {
    $set: { 'comments.$[element]': newComment }
  },
  {
    $set: { lastUpdateTime: { 
          '$cond': { 
              if: { $gte: [newComment.lastUpdated, '$lastUpdateTime'] },
              then: newComment.lastUpdated,
              else: '$lastUpdateTime',
            } 
         } 
      }
  }
],
{
  arrayFilters: [ {'element.id': newComment.id } ]
}
);

例如,在使用注解更新后:

{
  id: 390430,
  content: "new content",
  lastUpdated: <new time>
}

我希望我的主要目标是:

{
  _id: 932842242342354234,
  lastUpdateTime: <new time>,
  comments: [
    {
      id: 390430,
      content: "new content",
      lastUpdated: <new time>
    }
  ],
}
mbyulnm0

mbyulnm01#

我认为arrayFilters不适合您的场景,相反,使用聚合管道。
$map迭代comments数组中的每个元素,如果该元素与要更新的id匹配,则用newComment对象更新,否则保持现有值。

updateOne(
{ _id: documentId },
[
  {
    $set: { 
      'comments': {
        $map: {
          input: "$comments",
          in: {
            $cond: {
              if: { $eq: [ "$$this.id", newComment.id ] },
              then: newComment,
              else: "$$this"
            }
          }
        }
      }
    }
  },
  {
    $set: { lastUpdateTime: { 
          '$cond': { 
              if: { $gte: [newComment.lastUpdated, '$lastUpdateTime'] },
              then: newComment.lastUpdated,
              else: '$lastUpdateTime',
            } 
         } 
      }
  }
]
);

相关问题