Currently utilizing Mongo 4.4, I am attempting to execute an update operation with the aggregation pipeline using updateOne
to modify nested array elements. To target a specific array member for updating, I include an arrayFilter
in the options. However, encountering an error message stating:
arrayFilters may not be specified for pipeline-style updates.
An example query similar to what I'm working on is:
updateOne(
{ _id: <some_id>},
[
{
$set: { 'arr.$[element]': <new_value> }
},
{
$set: { somefield: { '$cond': { <the condition content> } } }
}
],
{
arrayFilters: [ {'element.id': <new_value>.id } ]
}
);
How can I resolve this issue?
UPDATE 1:
Illustrative document example:
{
_id: 932842242342354234,
lastUpdateTime: <old time>,
comments: [
{
id: 390430,
content: "original",
lastUpdated: <sime time>
}
],
}
The desired query involves updating a comment and simultaneously updating the main field lastEditTime
only if the lastUpdated
content has a timestamp later than the current lastEditTime
. The update operation would look as follows:
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 } ]
}
);
For instance, post an update with the comment:
{
id: 390430,
content: "new content",
lastUpdated: <new time>
}
The goal is to have the primary object transformed into:
{
_id: 932842242342354234,
lastUpdateTime: <new time>,
comments: [
{
id: 390430,
content: "new content",
lastUpdated: <new time>
}
],
}