|
1 | 1 | # Using Change Streams
|
2 | 2 |
|
3 |
| -MongoSwift 0.2.0 added support for [change streams](https://docs.mongodb.com/manual/changeStreams/), which allow applications to access real-time data changes. Applications can use change streams to subscribe to all data changes on a single collection, a database, or an entire deployment, and immediately react to them. Because change streams use the aggregation framework, applications can also filter for specific changes or transform the notifications at will. |
| 3 | +The driver supports [change streams](https://docs.mongodb.com/manual/changeStreams/), which allow applications to access real-time data changes. Applications can use change streams to subscribe to all data changes on a single collection, a database, or an entire deployment, and immediately react to them. Because change streams use the aggregation framework, applications can also filter for specific changes or transform the notifications at will. |
4 | 4 |
|
5 | 5 | **Note**: Change streams only work with MongoDB replica sets and sharded clusters.
|
6 | 6 |
|
7 | 7 | ## Examples
|
| 8 | +These examples use the driver's async/await APIs; for examples using `EventLoopFuture`s please see the [previous version of this guide](https://github.com/mongodb/mongo-swift-driver/blob/79c9683d56f92540f4065f40b9f55e1911a1ff5b/Guides/Change-Streams-Guide.md). |
8 | 9 |
|
9 |
| -### Open a Change Stream on a `MongoCollection<Document>` (MongoDB 3.6+) |
10 |
| -```swift |
11 |
| -let elg = MultiThreadedEventLoopGroup(numberOfThreads: 4) |
12 |
| -let client = try MongoClient(using: elg) |
13 |
| -let inventory = client.db("example").collection("inventory") |
| 10 | +### Open a Change Stream on a `MongoCollection` (MongoDB 3.6+) |
14 | 11 |
|
15 |
| -inventory.watch().flatMap { stream in // a `ChangeStream<ChangeStreamEvent<BSONDocument>>` |
16 |
| - stream.forEach { event in |
17 |
| - // process `ChangeStreamEvent<BSONDocument>` here |
18 |
| - } |
19 |
| -}.whenFailure { error in |
20 |
| - // handle error |
21 |
| -} |
| 12 | +We recommend to open and interact with change streams in their own `Task`s, and to terminate change streams by canceling their corresponding `Task`s. |
| 13 | +In the following example, change stream events will be processed asynchronously as they arrive on `changeStreamTask` until the `Task` is canceled. |
| 14 | +`ChangeStream` conforms to Swift's [`AsyncSequence` protocol](https://developer.apple.com/documentation/swift/asyncsequence) and so can be iterated |
| 15 | +over using a for-in loop. |
22 | 16 |
|
23 |
| -// perform some operations using `inventory`... |
24 |
| -``` |
25 |
| - |
26 |
| -### Open a Change Stream on a `MongoCollection<MyCodableType>` (MongoDB 3.6+) |
27 | 17 | ```swift
|
28 |
| -let elg = MultiThreadedEventLoopGroup(numberOfThreads: 4) |
29 |
| -let client = try MongoClient(using: elg) |
30 |
| -let inventory = client.db("example").collection("inventory", withType: MyCodableType.self) |
| 18 | +struct Item: Codable { |
| 19 | + let _id: BSONObjectID |
| 20 | + let name: String |
| 21 | + let cost: Int |
| 22 | + let count: Int |
| 23 | +} |
31 | 24 |
|
32 |
| -inventory.watch().flatMap { stream in // a `ChangeStream<ChangeStreamEvent<MyCodableType>>` |
33 |
| - stream.forEach { event in |
34 |
| - // process `ChangeStreamEvent<MyCodableType>` here |
| 25 | +let inventory = client.db("example").collection("inventory", withType: Item.self) |
| 26 | +let changeStreamTask = Task { |
| 27 | + for try await event in try await inventory.watch() { |
| 28 | + // process `ChangeStream<ChangeStreamEvent<Item>>` |
35 | 29 | }
|
36 |
| -}.whenFailure { error in |
37 |
| - // handle error |
38 | 30 | }
|
39 | 31 |
|
40 |
| -// perform some operations using `inventory`... |
| 32 | +// later... |
| 33 | +changeStreamTask.cancel() |
41 | 34 | ```
|
42 | 35 |
|
43 |
| -### Use a Custom `Codable` Type for the `fullDocument` Property of Returned `ChangeStreamEvent`s |
| 36 | +If you provide a pipeline to `watch` which transforms the shape of the returned documents, you will need to specify a type to use for the |
| 37 | +`ChangeStreamEvent.fullDocument` property. You can do this as follows when calling `watch`: |
| 38 | + |
44 | 39 | ```swift
|
45 |
| -let elg = MultiThreadedEventLoopGroup(numberOfThreads: 4) |
46 |
| -let client = try MongoClient(using: elg) |
47 |
| -let inventory = client.db("example").collection("inventory") |
| 40 | +struct ItemCount: Codable { |
| 41 | + let _id: BSONObjectID |
| 42 | + let count: Int |
| 43 | +} |
48 | 44 |
|
49 |
| -inventory.watch(withFullDocumentType: MyCodableType.self).flatMap { stream in // a `ChangeStream<ChangeStreamEvent<MyCodableType>>` |
50 |
| - stream.forEach { event in |
51 |
| - // process `ChangeStreamEvent<MyCodableType>` here |
| 45 | +let changeStreamTask = Task { |
| 46 | + let pipeline: [BSONDocument] = [["$unset": ["fullDocument.name", "fullDocument.cost"]]] |
| 47 | + for try await event in try await inventory.watch(pipeline, withFullDocumentType: ItemCount.self) { |
| 48 | + // process `ChangeStream<ChangeStreamEvent<ItemCount>>` |
52 | 49 | }
|
53 |
| -}.whenFailure { error in |
54 |
| - // handle error |
55 | 50 | }
|
56 | 51 |
|
57 |
| -// perform some operations using `inventory`... |
| 52 | +// later... |
| 53 | +changeStreamTask.cancel() |
58 | 54 | ```
|
59 | 55 |
|
60 |
| -### Use a Custom `Codable` Type for the Return type of `ChangeStream.next()` |
61 |
| -```swift |
62 |
| -let elg = MultiThreadedEventLoopGroup(numberOfThreads: 4) |
63 |
| -let client = try MongoClient(using: elg) |
64 |
| -let inventory = client.db("example").collection("inventory") |
| 56 | +You can also provide a type to use in place of `ChangeStreamEvent` altogether: |
65 | 57 |
|
66 |
| -inventory.watch(withEventType: MyCodableType.self).flatMap { stream in // a `ChangeStream<MyCodableType>` |
67 |
| - stream.forEach { event in |
68 |
| - // process `MyCodableType` here |
| 58 | +```swift |
| 59 | +let changeStreamTask = Task { |
| 60 | + for try await event in try await inventory.watch(withEventType: InventoryEvent.self) { |
| 61 | + // process `ChangeStream<ChangeStreamEvent<InventoryEvent>>` |
69 | 62 | }
|
70 |
| -}.whenFailure { error in |
71 |
| - // handle error |
72 | 63 | }
|
73 | 64 |
|
74 |
| -// perform some operations using `inventory`... |
| 65 | +// later... |
| 66 | +changeStreamTask.cancel() |
75 | 67 | ```
|
76 | 68 |
|
77 | 69 | ### Open a Change Stream on a `MongoDatabase` (MongoDB 4.0+)
|
| 70 | +You can also open a change stream on an entire database, which will observe events on all collections in the database: |
| 71 | + |
78 | 72 | ```swift
|
79 |
| -let elg = MultiThreadedEventLoopGroup(numberOfThreads: 4) |
80 |
| -let client = try MongoClient(using: elg) |
81 | 73 | let db = client.db("example")
|
82 | 74 |
|
83 |
| -db.watch().flatMap { stream in // a `ChangeStream<ChangeStreamEvent<BSONDocument>>` |
84 |
| - stream.forEach { event in |
85 |
| - // process `ChangeStreamEvent<BSONDocument>` here |
| 75 | +let changeStreamTask = Task { |
| 76 | + for try await event in try await db.watch() { |
| 77 | + // process `ChangeStream<ChangeStreamEvent<BSONDocument>>` |
86 | 78 | }
|
87 |
| -}.whenFailure { error in |
88 |
| - // handle error |
89 | 79 | }
|
90 | 80 |
|
91 |
| -// perform some operations using `db`... |
| 81 | +// later... |
| 82 | +changeStreamTask.cancel() |
92 | 83 | ```
|
93 | 84 |
|
94 |
| -Note: the types of the `fullDocument` property, as well as the return type of `ChangeStream.next()`, may be customized in the same fashion as the examples using `MongoCollection` above. |
| 85 | +Note: the type of the `ChangeStreamEvent.fullDocument` property, as well as the return type of `ChangeStream.next()`, may be customized in the same fashion as the examples using `MongoCollection` above by passing in `fullDocumentType` or `eventType` to `watch()`. |
95 | 86 |
|
96 | 87 | ### Open a Change Stream on a `MongoClient` (MongoDB 4.0+)
|
97 |
| -```swift |
98 |
| -let elg = MultiThreadedEventLoopGroup(numberOfThreads: 4) |
99 |
| -let client = try MongoClient(using: elg) |
| 88 | +You can also open a change stream on an entire cluster, which will observe events on all databases and collections: |
100 | 89 |
|
101 |
| -client.watch().flatMap { stream in // a `ChangeStream<ChangeStreamEvent<BSONDocument>>` |
102 |
| - stream.forEach { event in |
103 |
| - // process `ChangeStreamEvent<BSONDocument>` here |
| 90 | +```swift |
| 91 | +let changeStreamTask = Task { |
| 92 | + for try await event in try await client.watch() { |
| 93 | + // process `ChangeStream<ChangeStreamEvent<BSONDocument>>` |
104 | 94 | }
|
105 |
| -}.whenFailure { error in |
106 |
| - // handle error |
107 | 95 | }
|
108 | 96 |
|
109 |
| -// perform some operations using `client`... |
| 97 | +// later... |
| 98 | +changeStreamTask.cancel() |
110 | 99 | ```
|
111 | 100 |
|
112 |
| -Note: the types of the `fullDocument` property, as well as the return type of `ChangeStream.next()`, may be customized in the same fashion as the examples using `MongoCollection` above. |
| 101 | +Note: the type of the `ChangeStreamEvent.fullDocument` property, as well as the return type of `ChangeStream.next()`, may be customized in the same fashion as the examples using `MongoCollection` above by passing in `fullDocumentType` or `eventType` to `watch()`. |
113 | 102 |
|
114 | 103 | ### Resume a Change Stream
|
| 104 | +Change streams can be resumed from particular points in time using resume tokens. For example: |
| 105 | + |
115 | 106 | ```swift
|
116 |
| -let elg = MultiThreadedEventLoopGroup(numberOfThreads: 4) |
117 |
| -let client = try MongoClient(using: elg) |
118 | 107 | let inventory = client.db("example").collection("inventory")
|
119 | 108 |
|
120 |
| -inventory.watch().flatMap { stream -> EventLoopFuture<ChangeStream<ChangeStreamEvent<BSONDocument>>> in |
| 109 | +let changeStreamTask1 = Task { () -> ResumeToken? in |
| 110 | + let changeStream = try await inventory.watch() |
121 | 111 | // read the first change event
|
122 |
| - stream.next().flatMap { _ in |
123 |
| - // simulate an error by killing the stream |
124 |
| - stream.kill() |
125 |
| - }.flatMap { _ in |
126 |
| - // create a new change stream that starts after the first change event |
127 |
| - let resumeToken = stream.resumeToken |
128 |
| - return inventory.watch(options: ChangeStreamOptions(resumeAfter: resumeToken)) |
129 |
| - } |
130 |
| -}.flatMap { resumedStream in |
131 |
| - resumedStream.forEach { event in |
132 |
| - // process `ChangeStreamEvent<BSONDocument>` here |
| 112 | + _ = try await changeStream.next() |
| 113 | + // resume token to resume stream after the first event |
| 114 | + return changeStream.resumeToken |
| 115 | +} |
| 116 | + |
| 117 | +// Get resume token from the first task and change stream. |
| 118 | +guard let resumeToken = try await changeStreamTask1.value else { |
| 119 | + fatalError("Unexpectedly missing resume token after processing event") |
| 120 | +} |
| 121 | + |
| 122 | +let changeStreamTask2 = Task { |
| 123 | + let changeStream = try await inventory.watch(options: ChangeStreamOptions(resumeAfter: resumeToken)) |
| 124 | + for try await event in changeStream { |
| 125 | + // process ChangeStreamEvent |
133 | 126 | }
|
134 |
| -}.whenFailure { error in |
135 |
| - // handle error |
136 | 127 | }
|
137 | 128 |
|
138 |
| -// perform some operations using `inventory`... |
| 129 | +// later... |
| 130 | +changeStreamTask2.cancel() |
139 | 131 | ```
|
140 | 132 |
|
141 | 133 | ### Modify Change Stream Output
|
142 | 134 | ```swift
|
143 |
| -let elg = MultiThreadedEventLoopGroup(numberOfThreads: 4) |
144 |
| -let client = try MongoClient(using: elg) |
145 |
| -let inventory = client.db("example").collection("inventory") |
146 |
| - |
147 |
| -// Only include events where the changed document's username = "alice" |
148 |
| -let pipeline: [BSONDocument] = [ |
149 |
| - ["$match": ["fullDocument.username": "alice"]] |
150 |
| -] |
151 |
| - |
152 |
| -inventory.watch(pipeline).flatMap { stream in // a `ChangeStream<ChangeStreamEvent<BSONDocument>>` |
153 |
| - stream.forEach { event in |
154 |
| - // process `ChangeStreamEvent<BSONDocument>` here |
| 135 | +let inventory = client.db("example").collection("inventory", withType: Item.self) |
| 136 | + |
| 137 | +let changeStreamTask = Task { |
| 138 | + // Only include events where the changed document's count = 0 |
| 139 | + let pipeline: [BSONDocument] = [ |
| 140 | + ["$match": ["fullDocument.count": 0]] |
| 141 | + ] |
| 142 | + for try await event in try await inventory.watch(pipeline) { |
| 143 | + // process `ChangeStream<ChangeStreamEvent<Item>>` |
155 | 144 | }
|
156 |
| -}.whenFailure { error in |
157 |
| - // handle error |
158 | 145 | }
|
159 | 146 |
|
160 |
| -// perform some operations using `inventory`... |
| 147 | +// later... |
| 148 | +changeStreamTask.cancel() |
161 | 149 | ```
|
162 | 150 |
|
163 | 151 | ## See Also
|
164 |
| -- [MongoDB Change Streams documentation](https://docs.mongodb.com/manual/changeStreams/) |
| 152 | +- [MongoDB Change Streams documentation](https://docs.mongodb.com/manual/changeStreams/) |
0 commit comments