Skip to content

Instantly share code, notes, and snippets.

@riodw
Last active September 20, 2020 12:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save riodw/74a839ab6964bceda8ff799d3ad33442 to your computer and use it in GitHub Desktop.
Save riodw/74a839ab6964bceda8ff799d3ad33442 to your computer and use it in GitHub Desktop.
How to listen for changes to a MongoDB collection?

Check out this: Change Streams

January 10, 2018 - Release 3.6


It's new in mongodb 3.6 https://docs.mongodb.com/manual/release-notes/3.6/ 2018/01/10

$ mongod --version
db version v3.6.2

In order use changeStreams the database must be a Replication Set

More about Replication Sets: https://docs.mongodb.com/manual/replication/

Your Database will be a "Standalone" by default.

How to Convert a Standalone to a Replica Set: https://docs.mongodb.com/manual/tutorial/convert-standalone-to-replica-set/


The following example is a practical application for how you might use this.

  • Specifically for Node.

    /* file.js */
    'use strict'
    
    
    module.exports = function (
          app,
          io,
          User // Collection Name
    ) {
        // SET WATCH ON COLLECTION 
        const changeStream = User.watch();  
    
        // Socket Connection  
        io.on('connection', function (socket) {
            console.log('Connection!');
    
            // USERS - Change
            changeStream.on('change', function(change) {
                console.log('COLLECTION CHANGED');
    
                User.find({}, (err, data) => {
                    if (err) throw err;
      
                    if (data) {
                        // RESEND ALL USERS
                        socket.emit('users', data);
                    }
                });
            });
        });
    };
    /* END - file.js */
    

Useful links:
https://docs.mongodb.com/manual/tutorial/convert-standalone-to-replica-set
https://docs.mongodb.com/manual/tutorial/change-streams-example
https://docs.mongodb.com/v3.6/tutorial/change-streams-example
http://plusnconsulting.com/post/MongoDB-Change-Streams

@Anoirwork
Copy link

Dude you saved my life thanks 👍

@riodw
Copy link
Author

riodw commented Sep 20, 2020

🥳

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment