Created
September 12, 2018 09:55
-
-
Save christiansparre/d8b03a9ce840cb8237a181e4d5bf8544 to your computer and use it in GitHub Desktop.
MongoDB 4 concurrent transaction inserts to different collections
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System; | |
| using System.Collections.Generic; | |
| using System.Threading.Tasks; | |
| using MongoDB.Bson; | |
| using MongoDB.Driver; | |
| namespace MongoDB4Concurrency | |
| { | |
| class Program | |
| { | |
| static async Task Main(string[] args) | |
| { | |
| var url = new MongoUrl("mongodb://localhost:37017"); | |
| var databaseName = Guid.NewGuid().ToString(); | |
| var client = new MongoClient(url); | |
| var database = client.GetDatabase(databaseName); | |
| var documentCount = 1; | |
| var taskCount = 8; | |
| var tasks = new List<Task>(); | |
| for (int i = 0; i < taskCount; i++) | |
| { | |
| var i1 = i; | |
| tasks.Add(Task.Run(async () => | |
| { | |
| var coll = database.GetCollection<BsonDocument>(Guid.NewGuid().ToString()); | |
| await database.CreateCollectionAsync(coll.CollectionNamespace.CollectionName); | |
| using (var session = client.StartSession()) | |
| { | |
| session.StartTransaction(); | |
| try | |
| { | |
| for (int j = 0; j < documentCount; j++) | |
| { | |
| await coll.InsertOneAsync(session, new BsonDocument()); | |
| } | |
| await session.CommitTransactionAsync(); | |
| Console.WriteLine($"Task {i1}, success"); | |
| } | |
| catch (MongoCommandException e) | |
| { | |
| Console.WriteLine($"Task {i1}, fail: {e.ErrorMessage}"); | |
| session.AbortTransaction(); | |
| } | |
| } | |
| })); | |
| } | |
| await Task.WhenAll(tasks); | |
| Console.WriteLine("Complete"); | |
| new MongoClient(url).DropDatabase(databaseName); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment