Skip to content

Commit 9ba82a6

Browse files
CSHARP-2141: Add documentation sample for causal consistency.
1 parent c300351 commit 9ba82a6

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

tests/MongoDB.Driver.Examples/CausalConsistencyExamples.cs

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,41 @@ public void Causal_Consistency_Example_2()
106106
// End Causal Consistency Example 2
107107
}
108108
}
109+
110+
[Fact]
111+
public void Causal_Consistency_Example_3()
112+
{
113+
RequireServer.Check().SupportsCausalConsistency();
114+
115+
DropCollection(CreateClient(), "myDatabase", "myCollection");
116+
117+
// Start Tunable Consistency Controls Example
118+
var connectionString = "mongodb://localhost/?readPreference=secondaryPreferred";
119+
120+
var client = new MongoClient(connectionString);
121+
var database = client.GetDatabase("myDatabase");
122+
var collection = database.GetCollection<BsonDocument>("myCollection");
123+
124+
// Start client session, which is causally consistent by default
125+
using (var session = client.StartSession())
126+
{
127+
// Run causally related operations within the session
128+
collection.InsertOne(session, new BsonDocument("name", "Tom"));
129+
collection.UpdateOne(session,
130+
Builders<BsonDocument>.Filter.Eq("name", "Tom"),
131+
Builders<BsonDocument>.Update.Set("name", "John"));
132+
133+
foreach (var document in collection.Find(session, FilterDefinition<BsonDocument>.Empty).ToEnumerable())
134+
{
135+
// process document
136+
}
137+
}
138+
// End Tunable Consistency Controls Example
139+
140+
var result = collection.Find("{}").FirstOrDefault();
141+
RemoveIds(new[] { result });
142+
result.Should().Be("{ name: 'John' }");
143+
}
109144

110145
private IMongoClient CreateClient()
111146
{

0 commit comments

Comments
 (0)