1

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?

Rohit Nair
  • 628
  • 3
  • 7
  • 22
  • Does your example even work? According to the [watch method documentation](https://docs.mongodb.com/manual/reference/method/db.collection.watch/), `fullDocument` is an option, and should be given in the second argument of the method. – noam Jun 21 '20 at 11:20
  • 1
    You can project with change streams. – D. SM Jun 21 '20 at 12:39
  • Hi @noam it does work, I'm passing fullDocument as the only option. And since the method excepts an object and not positional arguments, it is ok if you only pass one key. – Rohit Nair Jun 22 '20 at 06:25
  • Yes sir @D.SM thats what I tried but couldn't get it working. To pass $project in the aggregate pipeline, since $project lets you choose which keys to hide or display. – Rohit Nair Jun 22 '20 at 06:27
  • I would also like to point out that, I'm not trying to show/hide an updated field, rather want to show an unchanged field with every update. Currently, I can get that field from the fullDocument, I want to reduce the amount of data mongo sends back to my node server which is what I'm trying to figure out. – Rohit Nair Jun 22 '20 at 06:45

1 Answers1

2

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 ;)

Rohit Nair
  • 628
  • 3
  • 7
  • 22