How to watch for changes to specific field of array in MongoDB change stream

Viewed 279

How am I able to watch only updates in "orders" field of array? For example, an item was added or removed from array.

I found a code below that should have solved the issue, but it only works if the field is not an array.

Data:

{
 "title": "hello", 
 "orders": [Object]
}

Code:

var pipeline = [
    {
      $match: {
        $and: [
          {'updateDescription.updatedFields.orders': {$exists: true}},
          {operationType: 'update'},
        ],
      },
    },
  ];

  var options = {fullDocument: 'updateLookup'};

  const restaurants = connection
    .collection('restaurants')
    .watch(pipeline, options);
1 Answers

An exemple which works for me:

{
                $match: {
                    // takes only the update and replace operation
                    operationType: { $in: ['update', 'replace']},
                    // when there is some commandIds. For update, commandIds are in the updateDescription.updatedFields.commandIds field,
                    // For replace, commandIds are in the fullDocument.commandIds field
                    $or: [
                        {$and: [
                            {'updateDescription.updatedFields.commandIds': {$ne: null}},
                            {$expr: {$gt: [{$size: "$updateDescription.updatedFields.commandIds"}, 0]}}
                        ]},
                        {$and: [
                            {'fullDocument.commandIds': {$ne: null}},
                            {$expr: {$gt: [{$size: "$fullDocument.commandIds"}, 0]}}
                        ]}
                    ]
                }
            }

because the result payload depends of the event (create, update or replace), you have to check for multiple location.

Related