$changeStream
Not supported by Elastic cluster.
The $changeStream aggregation stage opens a change stream cursor to monitor real-time changes to a collection. It returns change event documents when insert, update, replace, or delete operations occur.
Parameters
-
fullDocument: Specifies whether to return the full document for update operations. Options aredefaultorupdateLookup. -
resumeAfter: Optional. Resume token to continue from a specific point in the change stream. -
startAtOperationTime: Optional. Timestamp to start the change stream from. -
allChangesForCluster: Optional. Boolean value. Whentrue, watches all changes across the cluster (for admin database). Whenfalse(default), watches only the specified collection.
Example (MongoDB Shell)
The following example demonstrates using the $changeStream stage to monitor changes to a collection.
Query example
// Open change stream first const changeStream = db.inventory.aggregate([ { $changeStream: { fullDocument: "updateLookup" } } ]); // In another session, insert a document db.inventory.insertOne({ _id: 1, item: "Widget", qty: 10 }); // Back in the first session, read the change event if (changeStream.hasNext()) { print(tojson(changeStream.next())); }
Output
{
_id: { _data: '...' },
operationType: 'insert',
clusterTime: Timestamp(1, 1234567890),
fullDocument: { _id: 1, item: 'Widget', qty: 10 },
ns: { db: 'test', coll: 'inventory' },
documentKey: { _id: 1 }
}
Code examples
To view a code example for using the $changeStream aggregation stage, choose the tab for the language that you want to use: