MongoDB Change Streams Shell examples
Replica set setup
MongoDB Change Streams require a replica set to work (i.e. they don't work with a standalone MongoDB server). Here are the instructions to start your local, single-node MongoDB 3.6 replica set:
- Make sure MongoDB 3.6+ is installed and your machine and the MongoDB installation folder (containing tools such as
mongod) is added to your local path.
sh startRS.shto start a test, single-node replica set (in the
- If you've started your replica set for the first time, run
sh initiateRS.shto initialize your replica set.
mongo createProducts.jsto create products (one every second) in the
devicescollection of the
demodatabase in your replica set. All of the documents created with that script have a
quantityattribute greater or equal than 11.
- In a separate Terminal console, start
sh insertChangeStream.shto monitor inserts of the products into your database. Note that the script logs the first change it captures, simulates an app failure for 10 seconds and then catches up the inserts it missed (using a resume token).
- Stop the
insertChangeStream.shscript and the
mongo createProducts.jsprocess (with
sh updateChangeStream.shin a Terminal console to monitor quantity updates of documents in the
stockcollection. Specifically, this change stream only prints out document updates when the
quantityattributes is set to a value lower or equal than 10.
mongo updateProducts.jsto trigger
quantityupdates below 10 and watch changes being logged in the