Using mongodbdriver in version 2.10 in a C# project.
I have a document type as follows:
{
"_id" : ObjectId("609720e0fc341e5879c91779"),
"number" : "1"
}
Currently when creating a new object, I set the number manually:
var item = new Item();
item.number = getCollection<Item>().CountDocuments(new MongoDB.Bson.BsonDocument()) + 1;
await getCollection<Item>().InsertOneAsync(item);
When executed simultaneously one several machines, this sometimes leads to different documents with the same number, because the count can change between CountDocuments
and the insert.
{
"_id" : ObjectId("609720e0fc341e5879c91781"),
"number" : "2"
}
{
"_id" : ObjectId("609720e0fc341e5879c91783"),
"number" : "2"
}
Is there a way, to set this number on insert in an atomic command like so?
await getCollection<Item>().InsertOneAsync(item).OnInsertSet(item.number = db.collection<Items>.getCount();
Your help would be very much appreciated.