How to create a MongoDB change stream application

22 August,2019 by Jack Vamvas

In an earlier post How to create a MongoDB change stream for standalone I outlined setting up a change stream for a standalone MongoDB server. Essentially it requires initiating a Replicaset and then using the change stream feature to consume the output. 

When the change stream is available , a quick test is next in order. The test will print out the changes as they occur. The changes appearing will depending on the configuration. In the example below - the script is configured to monitor for changes in the  db = "mydb" and collection = "mycollection".

The script utilises the Collection method - db.collection.watch(). This method opens the change stream cursor and creates a data change notification . 

There is also usage of the JSON.stringify() converts the the Javascript object to a JSON string.

The base script comes from the article I've linked on How to create a MongoDB change stream for standalone

To execute the script from the command line execute : mongo my_script.js

 

conn = new Mongo("mongodb://localhost:27017/myauthdb?replicaSet=rs1");
db = conn.getDB("mydb");
collection = db.mycollection;

const changeStreamCursor = collection.watch();

pollStream(changeStreamCursor);

//this function polls a change stream and prints out each change as it comes in
function pollStream(cursor) {
  while (!cursor.isExhausted()) {
    if (cursor.hasNext()) {
      change = cursor.next();
      print(JSON.stringify(change));
    }
  }
  pollStream(cursor);
}


Author: Jack Vamvas (http://www.dba-ninja.com)


Share:

Verify your Comment

Previewing your Comment

This is only a preview. Your comment has not yet been posted.

Working...
Your comment could not be posted. Error type:
Your comment has been posted. Post another comment

The letters and numbers you entered did not match the image. Please try again.

As a final step before posting your comment, enter the letters and numbers you see in the image below. This prevents automated programs from posting comments.

Having trouble reading this image? View an alternate.

Working...

Post a comment on How to create a MongoDB change stream application


dba-ninja.com