InnerException: "An item with the same key has already been added"
using MongoDB.Bson.Serialization; using MongoDB.Driver; namespace MongoCounterDemo { class Program { private const string ConnectionString = "mongodb://user:password@host:27017/database"; static void Main(string[] args) { var customerCounter = new MongoDbCounter(ConnectionString, "Customers"); customerCounter.GetNextNumber(); } } class MongoDbCounter { #region Constants private const string CounterCollectionName = "Counters"; #endregion #region Fields private readonly string _connectionString; private readonly string _counterName; #endregion #region Constructor public MongoDbCounter(string connectionString, string counterName) { _connectionString = connectionString; _counterName = counterName; } #endregion #region Public Methods public int GetNextNumber() { var client = new MongoClient(_connectionString); var databaseName = new MongoUrl(_connectionString).DatabaseName; var db = client.GetDatabase(databaseName); var counterCol = db.GetCollection<Counter>(CounterCollectionName); var filter2 = Builders<Counter>.Filter.Eq("_id", _counterName); var update2 = Builders<Counter>.Update.Inc(c => c.Value, 1); var options2 = new FindOneAndUpdateOptions<Counter> { IsUpsert = true, ReturnDocument = ReturnDocument.After}; var result2 = counterCol.FindOneAndUpdate(filter2, update2, options2); return result2.Value; } #endregion } class Counter { static Counter() { BsonClassMap.RegisterClassMap<Counter>(cm => { cm.MapIdMember(c => c.Id); cm.MapProperty(c => c.Value); }); } public string Id { get; set; } public int Value { get; set; } } }