Docs Menu

Docs HomeDevelop ApplicationsMongoDB Manual

$changeStream (aggregation)

On this page

  • Definition
  • Examples
$changeStream

Returns a Change Stream cursor on a collection, a database, or an entire cluster. Must be used as the first stage in an aggregation pipeline.

The $changeStream stage has the following syntax:

{
$changeStream: {
allChangesForCluster: <boolean>,
fullDocument: <string>,
resumeAfter: <int>
startAfter: <document>
startAtOperationTime: <timestamp>
}
}
Parameter
Description
allChangesForCluster
Optional: Sets whether the change stream should include all changes in the cluster. May only be opened on the admin database.
fullDocument

Optional: Specifies whether change notifications include a copy of the full document when modified by update operations.

  • default: Change notifications do not include the full document for update operations.

  • updateLookup: Change notifications includes a copy of the document modified by the change. This document is the current majority-committed document or null if it no longer exists.

In the case of partial updates, the change notification also provides a description of the change.

resumeAfter
Specifies a resume token as the logical starting point for the change stream. Cannot be used with startAfter or startAtOperationTime fields.
startAfter
Specifies a resume token as the logical starting point for the change stream. Cannot be used with resumeAfter or startAtOperationTime fields.
startAtOperationTime
Specifies a time as the logical starting point for the change stream. Cannot be used with resumeAfter or startAfter fields.

To create a change stream cursor using the aggregation stage, run the aggregate command.

var cur = db.names.aggregate( [
{ $changeStream: {} }
] )

To open the cursor, run cur.

When the change stream detects a change, the next() method returns a change event notification. For example, after running cur.next(), MongoDB returns a document similar to the following:

{
"_id": {
_data: "8262E2EE54000000022B022C0100296E5A100448E5E3DD01364019AE8FE8C6859527E046645F6964006462E2EE54C8756C0D5CF6F0720004"
},
"operationType": "insert",
"clusterTime": Timestamp({ t: 1659039316, i: 2 }),
"fullDocument": {
"_id": ObjectId("62e2ee54c8756c0d5cf6f072"),
"name": "Walker Percy"
},
"ns": {
"db": "test",
"coll": "names"
},
"documentKey": { _id: ObjectId("62e2ee54c8756c0d5cf6f072") }
}

For more information on change stream notifications, see Change Events.

← $bucketAuto (aggregation)

On this page