Skip to content

Commit 9a1d776

Browse files
CSHARP-2720: Provide transaction example using new withTransaction API.
1 parent 02a44c5 commit 9a1d776

File tree

1 file changed

+103
-0
lines changed

1 file changed

+103
-0
lines changed
Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
/* Copyright 2019-present MongoDB Inc.
2+
*
3+
* Licensed under the Apache License, Version 2.0 (the "License");
4+
* you may not use this file except in compliance with the License.
5+
* You may obtain a copy of the License at
6+
*
7+
* http://www.apache.org/licenses/LICENSE-2.0
8+
*
9+
* Unless required by applicable law or agreed to in writing, software
10+
* distributed under the License is distributed on an "AS IS" BASIS,
11+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
* See the License for the specific language governing permissions and
13+
* limitations under the License.
14+
*/
15+
16+
using System.Threading;
17+
using FluentAssertions;
18+
using MongoDB.Bson;
19+
using MongoDB.Driver.Core.Clusters;
20+
using MongoDB.Driver.Core.Misc;
21+
using MongoDB.Driver.Core.TestHelpers.XunitExtensions;
22+
using Xunit;
23+
24+
namespace MongoDB.Driver.Examples.TransactionExamplesForDocs
25+
{
26+
public class WithTransactionExample1
27+
{
28+
[SkippableFact]
29+
public void Example1()
30+
{
31+
RequireServer.Check().ClusterTypes(ClusterType.ReplicaSet, ClusterType.Sharded).Supports(Feature.Transactions);
32+
33+
var connectionString = CoreTestConfiguration.ConnectionString.ToString();
34+
DropCollections(
35+
connectionString,
36+
CollectionNamespace.FromFullName("mydb1.foo"),
37+
CollectionNamespace.FromFullName("mydb2.bar"));
38+
string result = null;
39+
40+
// Start Transactions withTxn API Example 1
41+
// For a replica set, include the replica set name and a seedlist of the members in the URI string; e.g.
42+
// string uri = "mongodb://mongodb0.example.com:27017,mongodb1.example.com:27017/?replicaSet=myRepl";
43+
// For a sharded cluster, connect to the mongos instances; e.g.
44+
// string uri = "mongodb://mongos0.example.com:27017,mongos1.example.com:27017:27017/";
45+
var client = new MongoClient(connectionString);
46+
47+
// Prereq: Create collections. CRUD operations in transactions must be on existing collections.
48+
var database1 = client.GetDatabase("mydb1");
49+
var collection1 = database1.GetCollection<BsonDocument>("foo").WithWriteConcern(WriteConcern.WMajority);
50+
collection1.InsertOne(new BsonDocument("abc", 0));
51+
52+
var database2 = client.GetDatabase("mydb2");
53+
var collection2 = database2.GetCollection<BsonDocument>("bar").WithWriteConcern(WriteConcern.WMajority);
54+
collection2.InsertOne(new BsonDocument("xyz", 0));
55+
56+
// Step 1: Start a client session.
57+
using (var session = client.StartSession())
58+
{
59+
// Step 2: Optional. Define options to use for the transaction.
60+
var transactionOptions = new TransactionOptions(
61+
readPreference: ReadPreference.Primary,
62+
readConcern: ReadConcern.Local,
63+
writeConcern: WriteConcern.WMajority);
64+
65+
// Step 3: Define the sequence of operations to perform inside the transactions
66+
var cancellationToken = CancellationToken.None; // normally a real token would be used
67+
result = session.WithTransaction(
68+
(s, ct) =>
69+
{
70+
collection1.InsertOne(s, new BsonDocument("abc", 1), cancellationToken: ct);
71+
collection2.InsertOne(s, new BsonDocument("xyz", 999), cancellationToken: ct);
72+
return "Inserted into collections in different databases";
73+
},
74+
transactionOptions,
75+
cancellationToken);
76+
}
77+
//End Transactions withTxn API Example 1
78+
79+
result.Should().Be("Inserted into collections in different databases");
80+
81+
var collection1Documents = collection1.Find(FilterDefinition<BsonDocument>.Empty).ToList();
82+
collection1Documents.Count.Should().Be(2);
83+
collection1Documents[0]["abc"].Should().Be(0);
84+
collection1Documents[1]["abc"].Should().Be(1);
85+
86+
var collection2Documents = collection2.Find(FilterDefinition<BsonDocument>.Empty).ToList();
87+
collection2Documents.Count.Should().Be(2);
88+
collection2Documents[0]["xyz"].Should().Be(0);
89+
collection2Documents[1]["xyz"].Should().Be(999);
90+
}
91+
92+
// private methods
93+
private void DropCollections(string connectionString, params CollectionNamespace[] collectionNamespaces)
94+
{
95+
var client = new MongoClient(connectionString);
96+
foreach (var collectionNamespace in collectionNamespaces)
97+
{
98+
var database = client.GetDatabase(collectionNamespace.DatabaseNamespace.DatabaseName);
99+
database.DropCollection(collectionNamespace.CollectionName);
100+
}
101+
}
102+
}
103+
}

0 commit comments

Comments
 (0)