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

后端 未结 2 992
没有蜡笔的小新
没有蜡笔的小新 2021-02-08 19:46

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 c

2条回答
  •  说谎
    说谎 (楼主)
    2021-02-08 20:40

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

提交回复
热议问题