Search code examples
mongodbchangestreammongodb-3.6

Create mongo change stream in the mongo shell


MongoDB introduced change streams in their 3.6 release.
I wanted to implement mongo change stream in my code and wanted to understand how it works. I will implement using the java driver and it's pretty clear. But I wanted to know if there is there any way to open a change stream on in the mongo shell? Couldn't find much resources on that.


Solution

  • The db.collection.watch command opens a change stream cursor.

    For example:

    watchCursor = db.getSiblingDB("data").sensors.watch(
       [
          { $match : {"operationType" : "insert" } }
       ]
    )
    
    while (!watchCursor.isExhausted()){
       if (watchCursor.hasNext()){
          print(tojson(watchCursor.next()));
       }
    }
    

    Plenty more detail in the docs.