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

余生长醉 提交于 2020-08-04 11:45:33

问题


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

回答1:


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



回答2:


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'}
        ]
    }
};


来源:https://stackoverflow.com/questions/49621939/how-to-watch-for-changes-to-specific-fields-in-mongodb-change-stream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!