How to listen for changes to a MongoDB collection?

后端 未结 11 1612
不思量自难忘°
不思量自难忘° 2020-11-22 06:08

I\'m creating a sort of background job queue system with MongoDB as the data store. How can I \"listen\" for inserts to a MongoDB collection before spawning workers to proce

11条回答
  •  耶瑟儿~
    2020-11-22 06:55

    MongoDB version 3.6 now includes change streams which is essentially an API on top of the OpLog allowing for trigger/notification-like use cases.

    Here is a link to a Java example: http://mongodb.github.io/mongo-java-driver/3.6/driver/tutorials/change-streams/

    A NodeJS example might look something like:

     var MongoClient = require('mongodb').MongoClient;
        MongoClient.connect("mongodb://localhost:22000/MyStore?readConcern=majority")
         .then(function(client){
           let db = client.db('MyStore')
    
           let change_streams = db.collection('products').watch()
              change_streams.on('change', function(change){
                console.log(JSON.stringify(change));
              });
          });
    

提交回复
热议问题