When dealing with a nested array in a Mongo document, whether inserting, deleting or updating, you will use db.collection.update()
The problem I am running into is with the new Change Streams in v3.6+.
I need a way to differentiate between these operations in the change events that come from collection.watch()
Examples:
using document schema:
{
id: string,
array: [{id: string, value: string}]
}
insert to nested array:
collection.updateOne(
{id: 'some_id'},
{$push: {'array.$': {id: 'nested_id', value: 'new nested item'} } }
)
the change stream will respond with:
{
...
operationType: 'update',
updateDescription: {
updatedFields: 'array.0': {id: 'nested_id', value: 'new nested item'}
... }
}
update nested array item:
collection.updateOne(
{id: 'some_id', 'array.id': 'nested_id'},
{$set: {'array.$.name': 'new nested name' } }
)
the change stream will respond with:
{
...
operationType: 'update',
updateDescription: {
updatedFields: 'array.0.name': 'new nested name'
... }
}
delete nested array item:
collection.updateOne(
{id: 'some_id'},
{$pull: {array: {id: 'nested_id'} } }
)
the change stream will respond with:
{
...
operationType: 'update',
updateDescription: {
updatedFields: 'array': [...all items in array besides the one you just pulled]
... }
}
I can see a couple of janky ways to differentiate between these events, such as 'array.0.name'.split('.'), and if the last element is a number then it was a nested insert, otherwise it's an update or delete. That works, though I don't really like it.
But it doesn't seem like there is any good way to tell the different between a nested delete and insert. Any help on this issue would be great.