Filter only if operationType is 'update' in mongodb

Viewed 370

I'm listening to changes in my mongoDB replicaSet and using { fullDocument: 'updateLookup' } to get the fullDocument along with the changed field for operationType update

I wanted to remove certain fields from the fullDocument if the operationType is update

This is what I have done,

const filter = [{"$match":{"operationType":"update"}}, {"$project":{ "fullDocument._id": 0, "fullDocument.channel": 0, "fullDocument.user_id": 0, "fullDocument.first_name": 0, "fullDocument.last_name": 0, "fullDocument.profile_pic": 0, "fullDocument.email": 0, "fullDocument.number": 0, "fullDocument.updatedAt": 0, "fullDocument.createdAt": 0, "fullDocument.__v": 0}}];

const userDBChange = userChatModel.watch(filter, { fullDocument: 'updateLookup' });

The problem here is, I don't receive any other changes like - insert.

I figured out that the problem is in using "$match":{"operationType":"update"} if I remove it, I receive insert change updates but the $project is applied on it.

Is there a way to apply $project only on operationType:'update' while still letting the other changes come in unchanged (without applying filter on it)?

1 Answers

So after a few days of learning and trying new things, I have finally solved this issue.

I did the following:

const filter = 
[{ "$match": 
{ "operationType": {"$in" :["update", "insert"]} } }, 
{ "$project": {
    "fullDocument": {
        "$cond":{
            "if":{
                "$eq":["$operationType", "update"]
            },
            "then":"$fullDocument.client",
            "else":"$fullDocument"
        }
    }
}
}];

const userDBChange = userChatModel.watch(filter, { fullDocument: 'updateLookup' });

Happy coding, thanks!

Related