Search code examples
node.jsmongodbmongoosemongodb-queryreplicaset

Watch MongoDB to return changes along with a specified field value instead of returning fullDocument


I'm using watch() function of mongo to listen to changes made to a replicaSet, now I know I can get the whole document (fullDocument) by passing { fullDocument: 'updateLookup' } to the watch method, like :-

someModel.watch({ fullDocument: 'updateLookup' })

But what I really want to do is, get just one extra field which isn't changed every time a new update is made.

Let's say a field called 'user_id', currently I only get the updatedFields and the fullDocument which contains the 'user_id' along with a lot of other data which I would like to avoid.

What I have researched so far is Aggregation pipeline but couldn't figure out a way to implement it.

Can anybody help me figure out a way to this?


Solution

  • Thanks everyone for suggesting, as @D.SM pointed out I successfully implemented $project

    Like this :-

    const filter = [{"$match":{"operationType":"update"}}, {"$project":{"fullDocument.user_id": 1, "fullDocument.chats": 0, "fullDocument._id": 0, "fullDocument.first_name": 0, "fullDocument.last_name": 0 }}];
    

    Then passed it to watch() method

    Like:-

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

    Now I'm only getting user_id inside fullDocument object when the operationType is update hence reducing the data overhead returned from mongo

    Thanks again @D.SM and other's for trying to help me out ;)