|
13 | 13 | * limitations under the License.
|
14 | 14 | */
|
15 | 15 |
|
16 |
| -using System; |
17 |
| -using System.Threading; |
18 | 16 | using FluentAssertions;
|
19 | 17 | using MongoDB.Bson;
|
| 18 | +using MongoDB.Driver.Core.Misc; |
| 19 | +using MongoDB.Driver.Core.TestHelpers.XunitExtensions; |
20 | 20 | using MongoDB.Driver.Tests;
|
| 21 | +using System; |
| 22 | +using System.Threading; |
| 23 | +using System.Threading.Tasks; |
21 | 24 | using Xunit;
|
22 | 25 |
|
23 | 26 | namespace MongoDB.Driver.Examples
|
@@ -122,5 +125,58 @@ public void ChangeStreamExample3()
|
122 | 125 | next.FullDocument.Should().Be(documents[1]);
|
123 | 126 | }
|
124 | 127 | }
|
| 128 | + |
| 129 | + [Fact] |
| 130 | + public void ChangestreamExample4() |
| 131 | + { |
| 132 | + RequireServer.Check().Supports(Feature.AggregateAddFields); |
| 133 | + |
| 134 | + var client = DriverTestConfiguration.Client; |
| 135 | + var database = client.GetDatabase("ChangeStreamExamples"); |
| 136 | + database.DropCollection("inventory"); |
| 137 | + |
| 138 | + var cancelationTokenSource = new CancellationTokenSource(); |
| 139 | + try |
| 140 | + { |
| 141 | + var document = new BsonDocument("username", "alice"); |
| 142 | + |
| 143 | + Task.Run(() => |
| 144 | + { |
| 145 | + var inventoryCollection = database.GetCollection<BsonDocument>("inventory"); |
| 146 | + |
| 147 | + while (!cancelationTokenSource.IsCancellationRequested) |
| 148 | + { |
| 149 | + Thread.Sleep(TimeSpan.FromMilliseconds(100)); |
| 150 | + document["_id"] = ObjectId.GenerateNewId(); |
| 151 | + inventoryCollection.InsertOne(document); |
| 152 | + } |
| 153 | + }, cancelationTokenSource.Token); |
| 154 | + |
| 155 | + // Start Changestream Example 4 |
| 156 | + var pipeline = new EmptyPipelineDefinition<ChangeStreamDocument<BsonDocument>>() |
| 157 | + .Match(change => |
| 158 | + change.FullDocument["username"] == "alice" || |
| 159 | + change.OperationType == ChangeStreamOperationType.Delete) |
| 160 | + .AppendStage<ChangeStreamDocument<BsonDocument>, ChangeStreamDocument<BsonDocument>, BsonDocument>( |
| 161 | + "{ $addFields : { newField : 'this is an added field!' } }"); |
| 162 | + |
| 163 | + var collection = database.GetCollection<BsonDocument>("inventory"); |
| 164 | + using (var changeStream = collection.Watch(pipeline)) |
| 165 | + { |
| 166 | + using (var enumerator = changeStream.ToEnumerable().GetEnumerator()) |
| 167 | + { |
| 168 | + if (enumerator.MoveNext()) |
| 169 | + { |
| 170 | + var next = enumerator.Current; |
| 171 | + } |
| 172 | + } |
| 173 | + } |
| 174 | + // End Changestream Example 4 |
| 175 | + } |
| 176 | + finally |
| 177 | + { |
| 178 | + cancelationTokenSource.Cancel(); |
| 179 | + } |
| 180 | + } |
125 | 181 | }
|
126 | 182 | }
|
0 commit comments