Skip to content
Advertisement

MongoDB – How to use arrayFilters in pipeline-style for update

I use Mongo 4.4 and I try to perform an update with the aggregation pipeline using updateOne that updates the nested array elements. In order to update the specific array member I use an arrayFilter in the option but for some reason, I get the error message:

arrayFilters may not be specified for pipeline-style updates.

The query is something like this:

JavaScript

How to fix it?

EDIT 1:

An example of a document is:

JavaScript

The query I want to do is update a comment and at the same time update the main object’s field lastEditTime only if the content lastUpdated has a time that is after the current lastEditTime of the current document. So the update is:

JavaScript

So for example after an update with the comment:

JavaScript

I want my main object to be:

JavaScript

Advertisement

Answer

I think the arrayFilters is not suitable for your scenario. Instead, using the aggregation pipeline.

With $map to iterate every element in comments array. If the element is matched with the id to be updated, then update with newComment object, else remain the existing value.

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement