How to create a MongoDB change stream application

22 August,2019 by Rambler

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 - 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 =;


//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 =;

Author: Rambler (


Verify your Comment

Previewing your Comment

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

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.


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