我使用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>
}
],
}
1条答案
按热度按时间mbyulnm01#
我认为
arrayFilters
不适合您的场景,相反,使用聚合管道。用
$map
迭代comments
数组中的每个元素,如果该元素与要更新的id
匹配,则用newComment
对象更新,否则保持现有值。