Mongo Change Stream w/pipeline returning ALL changes to the collection

45 Views Asked by At

Following the applicable MongoDB Change Streams documentation (https://www.mongodb.com/docs/manual/changeStreams/#modify-change-stream-output) I am not receiving the expected results.

The Collection has Documents from several locations (field = "location") such as "CHS", "SAN", "ATL", etc.

I want to filter the incoming Change Stream Events for a specific location only (based on the Users current location).

const locationFilter = "CHS";
const mongo = mongoApp.currentUser.mongoClient(MONGODB_DATASOURCE);
const collection = mongo
        .db(MONGODB_DATABASE)
        .collection(MONGODB_COLLECTION);
const pipeline = [ { $match: { "fullDocument.location": locationFilter } } ];
const changeStream = collection.watch(pipeline, { fullDocument: "updateLookup" });
try {
        for await (const change of changeStream) {
          console.log("ChangeStream new event: ", change);
        }
} catch (error) {
        console.error(error);
      }

console log example result

The console log shows each change event received, along with the fullDocument for each, but the events are not limited to location="CHS" as desired. Instead I receive change events for every location in the Collection.

Since I am using React and the MongoDB library "realm-web" I have also tried modifying the pipeline as described in the Documentation (https://www.mongodb.com/docs/realm/web/mongodb/#watch-for-changes-in-a-collection-with-a-filter) like the following:

const pipeline = [ { $filter: { "fullDocument.location": locationFilter } } ];

None of these variations have changed the results. Still receiving events for all locations.

So I am looking for advice as to how to limit the events to only be for the specified location only.

0

There are 0 best solutions below