Zack Sloane
Zack Sloane

Reputation: 411

How to watch for changes to specific fields in MongoDB change stream

I am using the node driver for mongodb to initiate a change stream on a document that has lots of fields that update continuously (via some logic on the insert/update end that calls $set with only the fields that changed), but I would like to watch only for changes to a specific field. My current attempt at this is below but I just get every update even if the field isn't part of the update.

I think the "updateDescription.updatedFields" is what I am after but the code I have so far just gives me all the updates.

What would the proper $match filter look like to achieve something like this? I thought maybe checking if it's $gte:1 might be a hack to get it to work but I still just get every update. I've tried $inc to see if the field name is in "updatedFields" as well but that didn't seem to work either.

const MongoClient = require('mongodb').MongoClient;

const uri = 'mongodb://localhost:27017/?replicaSet=rs0';
MongoClient.connect(uri, function(err, client) {

    const db = client.db('mydb');
    // Connect using MongoClient
    var filter = {
        $match: {
            "updateDescription.updatedFields.SomeFieldA": { $gte : 1 },
            operationType: 'update'
        }
    };

    var options = { fullDocument: 'updateLookup' };
    db.collection('somecollection').watch(filter, options).on('change', data => {
        console.log(new Date(), data);
    });
});

Upvotes: 16

Views: 16500

Answers (2)

Zack Sloane
Zack Sloane

Reputation: 411

So i figured this out...

For anyone else interested: My "pipeline" (filter, in my example) needs to be an array

this works...

const MongoClient = require('mongodb').MongoClient;

const uri = 'mongodb://localhost:27017/?replicaSet=rs0';
MongoClient.connect(uri, function(err, client) {

    const db = client.db('mydb');
    // Connect using MongoClient
    var filter = [{
        $match: {
            $and: [
                { "updateDescription.updatedFields.SomeFieldA": { $exists: true } },
                { operationType: "update" }]
        }
    }];

    var options = { fullDocument: 'updateLookup' };
    db.collection('somecollection').watch(filter, options).on('change', data => 
    {
        console.log(new Date(), data);
    });
});

Upvotes: 15

Jerren Saunders
Jerren Saunders

Reputation: 1435

I'm looking for something similar, but from the blog post at https://www.mongodb.com/blog/post/an-introduction-to-change-streams, it looks like you might need to change your filter to:

var filter = {
    $match: {
        $and: [
            { "updateDescription.updatedFields.SomeFieldA": { $exists: true } },
            { operationType: 'update'}
        ]
    }
};

Upvotes: 1

Related Questions