$changeStream
The `$changeStream` stage returns a change stream cursor that tracks changes to a collection. Change streams allow applications to access real-time data changes without the complexity and risk of tailing the oplog.
Syntax
{
$changeStream: {
fullDocument: <string>,
fullDocumentBeforeChange: <string>,
resumeAfter: <document>,
startAfter: <document>,
startAtOperationTime: <timestamp>
}
}
Parameters
fullDocument
stringOptional. Specifies whether to return the full document for update operations. Options: "updateLookup", "whenAvailable", "required".
fullDocumentBeforeChange
stringOptional. Specifies whether to return the full document as it was before the change. Options: "whenAvailable", "required", "off".
resumeAfter
objectOptional. A resume token to resume the change stream after a specific change event.
startAfter
objectOptional. A resume token to start the change stream after a specific event, even if the token is invalidated.
startAtOperationTime
objectOptional. A timestamp to start the change stream from a specific point in time.
Examples
Sample Data
{
"_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4",
"name": "First Up Consultants | Beverage Shop",
"sales": { "totalSales": 75670 }
}
Watch for changes
Open a change stream to monitor all changes to the collection.
This query creates a change stream cursor for real-time updates.
Query:
db.stores.aggregate([
{ $changeStream: {} }
])
Output:
[
{
"_id": { "_data": "..." },
"operationType": "insert",
"fullDocument": {
"_id": "new-store-id",
"name": "New Store"
}
}
]
Watch with full document lookup
Monitor changes and return the full updated document.
This query includes the complete document after updates.
Query:
db.stores.aggregate([
{ $changeStream: { fullDocument: "updateLookup" } }
])
Output:
[
{
"_id": { "_data": "..." },
"operationType": "update",
"fullDocument": {
"_id": "store-id",
"name": "Updated Store Name",
"sales": { "totalSales": 80000 }
}
}
]