|
| 1 | +.. _golang-watch-changes: |
| 2 | + |
| 3 | +================= |
| 4 | +Watch for Changes |
| 5 | +================= |
| 6 | + |
| 7 | +.. default-domain:: mongodb |
| 8 | + |
| 9 | +.. contents:: On this page |
| 10 | + :local: |
| 11 | + :backlinks: none |
| 12 | + :depth: 2 |
| 13 | + :class: singlecol |
| 14 | + |
| 15 | +Overview |
| 16 | +-------- |
| 17 | + |
| 18 | +In this guide, you can learn how to monitor document changes with a change stream. |
| 19 | + |
| 20 | +A change stream outputs new change events, providing access to real-time data changes. |
| 21 | +You can open a change stream on a collection, database, or client object. |
| 22 | + |
| 23 | +Sample Data |
| 24 | +~~~~~~~~~~~ |
| 25 | + |
| 26 | +To run the examples in this guide, load these documents into the |
| 27 | +``tea.ratings`` collection with the following |
| 28 | +snippet: |
| 29 | + |
| 30 | +.. literalinclude:: /includes/fundamentals/code-snippets/CRUD/sort.go |
| 31 | + :language: go |
| 32 | + :dedent: |
| 33 | + :start-after: begin insertDocs |
| 34 | + :end-before: end insertDocs |
| 35 | + |
| 36 | +.. tip:: Non-existent Databases and Collections |
| 37 | + |
| 38 | + If the necessary database and collection don't exist when |
| 39 | + you perform a write operation, the server implicitly creates |
| 40 | + them. |
| 41 | + |
| 42 | +Each document contains a rating for a type of tea that corresponds to the ``type`` |
| 43 | +and ``rating`` fields. |
| 44 | + |
| 45 | +.. note:: |
| 46 | + |
| 47 | + Each example truncates the ``_data``, ``clusterTime``, and ``ObjectID`` values |
| 48 | + because the driver generates them uniquely. |
| 49 | + |
| 50 | +Open a Change Stream |
| 51 | +-------------------- |
| 52 | + |
| 53 | +To open a change stream, use the ``Watch()`` method. The ``Watch()`` method requires a context |
| 54 | +parameter and a pipeline parameter. To return all changes, pass in an empty Pipeline object. |
| 55 | + |
| 56 | +Example |
| 57 | +~~~~~~~ |
| 58 | + |
| 59 | +The following example opens a change stream on the ``tea.ratings`` collection and |
| 60 | +outputs all changes: |
| 61 | + |
| 62 | +.. code-block:: go |
| 63 | + |
| 64 | + coll := client.Database("tea").Collection("ratings") |
| 65 | + |
| 66 | + // open a change stream with an empty pipeline parameter |
| 67 | + changeStream, err := coll.Watch(context.TODO(), mongo.Pipeline{}) |
| 68 | + if err != nil { |
| 69 | + panic(err) |
| 70 | + } |
| 71 | + defer changeStream.Close(context.TODO()) |
| 72 | + |
| 73 | + // iterate over the cursor to print the change stream events |
| 74 | + for changeStream.Next(context.TODO()) { |
| 75 | + fmt.Println(changeStream.Current) |
| 76 | + } |
| 77 | + |
| 78 | +If you modify the ``tea.ratings`` collection in a separate shell, this code will print |
| 79 | +your changes. Inserting a document with a ``type`` value of ``"White Peony"`` and a |
| 80 | +``rating`` value of ``4`` will output the following change event: |
| 81 | + |
| 82 | +.. code-block:: go |
| 83 | + :copyable: false |
| 84 | + |
| 85 | + map[_id:map[_data:...] clusterTime: {...} documentKey:map[_id:ObjectID("...")] |
| 86 | + fullDocument:map[_id:ObjectID("...") rating:4 type:White Peony] ns: |
| 87 | + map[coll:ratings db:tea] operationType:insert] |
| 88 | + |
| 89 | +Modify the Change Stream Output |
| 90 | +------------------------------- |
| 91 | + |
| 92 | +Use the pipeline parameter to modify the change stream output. This parameter allows you to |
| 93 | +only watch for certain change events. Format the pipeline parameter as an array of documents, |
| 94 | +with each document representing an aggregation stage. |
| 95 | + |
| 96 | +You can use the following pipeline stages in this parameter: |
| 97 | + |
| 98 | +- ``$addFields`` |
| 99 | +- ``$match`` |
| 100 | +- ``$project`` |
| 101 | +- ``$replaceRoot`` |
| 102 | +- ``$replaceWith`` |
| 103 | +- ``$redact`` |
| 104 | +- ``$set`` |
| 105 | +- ``$unset`` |
| 106 | + |
| 107 | +Example |
| 108 | +~~~~~~~ |
| 109 | + |
| 110 | +The following example opens a change stream on the ``tea`` database, but only watches for |
| 111 | +new delete operations: |
| 112 | + |
| 113 | +.. code-block:: go |
| 114 | + |
| 115 | + db := client.Database("tea") |
| 116 | + |
| 117 | + pipeline := bson.D{{"$match", bson.D{{"operationType", "delete"}}}} |
| 118 | + changeStream, err := db.Watch(context.TODO(), mongo.Pipeline{pipeline}) |
| 119 | + if err != nil { |
| 120 | + panic(err) |
| 121 | + } |
| 122 | + defer changeStream.Close(context.TODO()) |
| 123 | + |
| 124 | + for changeStream.Next(context.TODO()) { |
| 125 | + fmt.Println(changeStream.Current) |
| 126 | + } |
| 127 | + |
| 128 | +If you delete the ``tea.ratings`` document with a ``type`` value of |
| 129 | +``"White Peony"`` in a separate shell, this code will output the following: |
| 130 | + |
| 131 | +.. code-block:: go |
| 132 | + :copyable: false |
| 133 | + |
| 134 | + {"_id": {"_data": "..."},"operationType": "delete","clusterTime": |
| 135 | + {"$timestamp":{"t":"...","i":"..."}},"ns": {"db": "tea","coll": "ratings"}, |
| 136 | + "documentKey": {"_id": {"$oid":"..."}}} |
| 137 | + |
| 138 | +.. note:: |
| 139 | + |
| 140 | + The ``Watch()`` method was called on the ``tea`` database, so the code outputs |
| 141 | + new delete operations in any ``tea`` collection. |
| 142 | + |
| 143 | + |
| 144 | +Modify the Behavior of Watch() |
| 145 | +------------------------------ |
| 146 | + |
| 147 | +Use an opts parameter to modify the behavior of the ``Watch()`` method. |
| 148 | + |
| 149 | +You can specify the following options in the opts parameter: |
| 150 | + |
| 151 | +- ``ResumeAfter`` |
| 152 | +- ``StartAfter`` |
| 153 | +- ``FullDocument`` |
| 154 | +- ``BatchSize`` |
| 155 | +- ``MaxAwaitTime`` |
| 156 | +- ``Collation`` |
| 157 | +- ``StartAtOperationTime`` |
| 158 | + |
| 159 | +For more information on these fields, visit the |
| 160 | +:manual:`MongoDB manual </reference/method/Mongo.watch/#mongodb-method-Mongo.watch>`. |
| 161 | + |
| 162 | +Example |
| 163 | +~~~~~~~ |
| 164 | + |
| 165 | +The following example calls the ``Watch()`` method on the ``tea.ratings`` collection. It |
| 166 | +specifies the ``FullDocument`` opts parameter to output a copy of the entire modified document: |
| 167 | + |
| 168 | +.. code-block:: go |
| 169 | + |
| 170 | + coll := client.Database("tea").Collection("ratings") |
| 171 | + opts := options.ChangeStream().SetFullDocument(options.UpdateLookup) |
| 172 | + |
| 173 | + changeStream, err := coll.Watch(context.TODO(), mongo.Pipeline{}, opts) |
| 174 | + if err != nil { |
| 175 | + panic(err) |
| 176 | + } |
| 177 | + defer changeStream.Close(context.TODO()) |
| 178 | + |
| 179 | + for changeStream.Next(context.TODO()) { |
| 180 | + fmt.Println(changeStream.Current) |
| 181 | + } |
| 182 | + |
| 183 | +If you update the ``rating`` value of the ``"Masala"`` tea from ``10`` to ``9``, |
| 184 | +this code outputs the following: |
| 185 | + |
| 186 | +.. code-block:: go |
| 187 | + :copyable: false |
| 188 | + |
| 189 | + {"_id": {"_data": "..."},"operationType": "update","clusterTime": {"$timestamp": |
| 190 | + {"t":"...","i":"..."}},"fullDocument": {"_id": {"$oid":"..."},"type": "Masala","rating": |
| 191 | + {"$numberInt":"9"}}, "ns": {"db": "tea","coll": "ratings"},"documentKey": {"_id": |
| 192 | + {"$oid":"..."}}, "updateDescription": {"updatedFields": {"rating": {"$numberInt":"9"}}, |
| 193 | + "removedFields": [],"truncatedArrays": []}} |
| 194 | + |
| 195 | +Without specifying the ``FullDocument`` option, the same update operation no longer |
| 196 | +outputs the ``"fullDocument"`` value. |
| 197 | + |
| 198 | +Additional Information |
| 199 | +---------------------- |
| 200 | + |
| 201 | +For a runnable example of a change stream, see :ref:`golang-watch`. |
| 202 | + |
| 203 | +For more information on change streams, see :manual:`Change Streams </changeStreams/>`. |
| 204 | + |
| 205 | +API Documentation |
| 206 | +~~~~~~~~~~~~~~~~~ |
| 207 | + |
| 208 | +To learn more about the ``Watch()`` method, visit the following API documentation links: |
| 209 | + |
| 210 | +- `Watch() for collections <{+api+}/mongo#Collection.Watch>`__ |
| 211 | +- `Watch() for databases <{+api+}/mongo#Database.Watch>`__ |
| 212 | +- `Watch() for clients <{+api+}/mongo#Client.Watch>`__ |
0 commit comments