mongodb changestream “pipeline” not working nodejs

390 Views Asked by At

I have the following change stream but it does not function changed is not logged once I update using mongo compass.

var pipeline = [
  { $match: { _id: ObjectId(id) } }
];
try {
  const collection = client.db("mydb").collection("shop");
  const changeStream = collection.watch(pipeline);
  changeStream.on('change', (next) => {
    //console.log(next);
    console.log('changed')
  }, err => {
    console.log(err);
  });
} catch (err) {
  console.log(err)
}
1

There are 1 best solutions below

0
On

Is the problem that you don't normally update the _id of a document in a collection? If, for some reason, you are updating the _id then maybe the problem is in how you're referencing your $match. This works for me:

const pipeline01 = [
  { $match: { 'updateDescription.updatedFields.fieldIamInterestedIn': { $ne: undefined } } },
  { $project: { 'fullDocument._id': 1, 'fullDocument.anotherFieldIamInterestedIn': 1 } },
];
theCollectionIamWatching.watch(pipeline01, { fullDocument: 'updateLookup' }).on('change', async (data) => {
// do the thing I want to do using data.fullDocument
});