MongoDB Change Broadcaster
A real-time change stream broadcaster for MongoDB, supporting multiple delivery channels (WebSocket, Redis, HTTP, etc.) with extensible architecture.
Read the blog post on the implementation here.
Features
- 📡 Listen to MongoDB change streams
- 🚀 Built-in channels: WebSocket, Redis, HTTP, and Database Logging
- 🔌 Extensible architecture for custom channels
- ⚡ Async-first implementation
- 🛠️ Configurable pipelines and filtering
Installation
pip install mongo-broadcaster
# Optional dependencies for specific channels:
pip install mongo_broadcaster[fastapi] # WebSocket
pip install mongo_broadcaster[redis] # Redis Pub/Sub support
Basic Usage
from mongo_broadcaster import (
MongoChangeBroadcaster,
BroadcasterConfig,
CollectionConfig
)
from mongo_broadcaster.channels import WebSocketChannel
# Initialize with MongoDB connection
config = BroadcasterConfig(
mongo_uri="mongodb://localhost:27017",
collections=[
CollectionConfig(
collection_name="users",
fields_to_watch=["name", "email"],
recipient_identifier="fullDocument._id"
)
]
)
broadcaster = MongoChangeBroadcaster(config)
broadcaster.add_channel(WebSocketChannel())
# Start listening (typically in your app startup)
await broadcaster.start()
Built-in Channels
| Channel | Description | Ideal For |
|---|---|---|
WebSocketChannel |
Real-time browser updates | Live dashboards |
RedisPubSubChannel |
Pub/Sub messaging | Microservices |
HTTPCallbackChannel |
Webhook notifications | Third-party integrations |
DatabaseChannel |
Persistent change logging | Audit trails |
Extending with Custom Channels
Implement your own channel by subclassing BaseChannel:
from mongo_broadcaster.channels.base import BaseChannel
from typing import Any, Dict
class CustomMQTTChannel(BaseChannel):
def __init__(self, broker_url: str):
self.broker_url = broker_url
self.client = None
async def connect(self):
"""Initialize your connection"""
self.client = await setup_mqtt_client(self.broker_url)
async def send(self, recipient: str, message: Dict[str, Any]):
"""Send to specific recipient"""
await self.client.publish(f"changes/{recipient}", message)
async def broadcast(self, message: Dict[str, Any]):
"""Send to all subscribers"""
await self.client.publish("changes/all", message)
async def disconnect(self):
"""Clean up resources"""
await self.client.disconnect()
# Usage:
broadcaster.add_channel(CustomMQTTChannel("mqtt://localhost"))
Configuration Options
CollectionConfig
CollectionConfig(
collection_name: str,
database_name: Optional[str] = None,
# Fields to include in change events
fields_to_watch: List[str] = [],
# Dot-notation path to identify recipients (e.g., "fullDocument._id")
recipient_identifier: Optional[str] = None,
# MongoDB change stream options
change_stream_config: ChangeStreamConfig = ChangeStreamConfig()
)
Examples
FastAPI WebSocket Endpoint
from fastapi import FastAPI, WebSocket
app = FastAPI()
ws_channel = WebSocketChannel()
@app.websocket("/ws/{client_id}")
async def websocket_endpoint(websocket: WebSocket, client_id: str):
await ws_channel.connect(client_id, websocket)
try:
while True:
await websocket.receive_text()
except WebSocketDisconnect:
await ws_channel.disconnect(client_id)
Please see the examples folder for more.
Contributing
To add new channels:
- Create a subclass of
BaseChannel - Implement required methods:
connect()send()broadcast()disconnect()
- Submit a PR!
License
MIT
TODO
- Write tests
Metadata
Release files for mongo-broadcaster 0.1.6
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | |
|---|---|---|---|
| mongo_broadcaster-0.1.6.tar.gz | 12.9 kB | Details |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Reset |
|---|---|---|---|---|
| mongo_broadcaster-0.1.6-py3-none-any.whl | Python 3 | none | any | Details |
Total release size: 29.1 kB
Release files / mongo_broadcaster-0.1.6.tar.gz
| Download URL | mongo_broadcaster-0.1.6.tar.gz |
|---|---|
| Size | 12.9 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
4343f50039d27fcf39c0b414af5707fb1baaff58a69740bcfbf5b3a9a24402c6
|
|
BLAKE2b-256 checksum How to use checksums |
c8019a8862cebf66bcd281ef84f964728aaa4db31ac1d9f4c8cad3c924cb4961
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.1.0 CPython/3.12.7
|
Release files / mongo_broadcaster-0.1.6-py3-none-any.whl
| Download URL | mongo_broadcaster-0.1.6-py3-none-any.whl |
|---|---|
| Size | 16.1 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
6a655a1889f55c4720526f6404ff7c1c11bb7954e6b513566ca3889bf5a27f7e
|
|
BLAKE2b-256 checksum How to use checksums |
6009ddce248fb44e9075bc7d39707a3e1e98e4322c23d101648f5ed7efbad42f
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.1.0 CPython/3.12.7
|