Subscribe to MongoDB Change Streams Via WebSockets
Rate this tutorial
allow applications to access real-time data changes without the complexity and risk of tailing the . Applications can use change streams to subscribe to all data changes on a single collection, a database, or an entire deployment, and immediately react to them. Because change streams use the aggregation framework, applications can also filter for specific changes or transform the notifications at will.
To allow clients to subscribe to your change stream via WebSockets, you must first create a WebSocket server. This WebSocket server, written in Python and using Tornado, proxies any new data from the change stream to your connected clients.
As clients connect and disconnect from the WebSocket server, they trigger the
When a client connects, your server stores a reference to it in the
connected_clientsset. This allows it to push new data to the client when it is received from the change stream. Likewise, when a client disconnects from the server, it is removed from the set of connected clients, so your server does not try to push updates on a connection which no longer exists.
It is worth noting that the server does not have a
on_messagehandler. As WebSockets are bi-directional, typically a WebSocket server has a
on_messagemethod. When the client sends data to the server, it invokes this method to handle the incoming message. However, as you are only using the WebSocket connection to push change stream data to the connected clients, your WebSocket connection is essentially mono-directional, and your server does not have a method for handling inbound data.
When you have new data from the change stream, you pass it to the WebSocket server using the
on_changemethod. This method formats the change stream data into a string ready to be pushed out to the connected clients. This push occurs in the
send_updatesmethod. Within this method, you loop over all clients in the
connected_clientsset and use the
write_messageaction to write the data to the client's WebSocket connection.
watchfunction is attached to your Tornado loop as a callback.
You can use Tornado to serve this web page as well.
To try the example for yourself:
- install the requirements.
- set the required environmental variables.
- run the Python script.
In this article, you have subscribed to all changes on a single collection. However, you can use change streams to subscribe to all data changes on a single collection, a database, or even an entire deployment. And, because change streams use the , applications can also filter for specific changes or transform the notifications.