Skip to content

Instantly share code, notes, and snippets.

@christiansparre
Created September 12, 2018 09:55
Show Gist options
  • Select an option

  • Save christiansparre/d8b03a9ce840cb8237a181e4d5bf8544 to your computer and use it in GitHub Desktop.

Select an option

Save christiansparre/d8b03a9ce840cb8237a181e4d5bf8544 to your computer and use it in GitHub Desktop.
MongoDB 4 concurrent transaction inserts to different collections
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