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
Leave a Reply