В качестве примера здесь :
var client = new MongoClient(connectionString);
MongoServer server = client.GetServer();
MongoDatabase db = server.GetDatabase("myDatabase");
var counterCol = db.GetCollection("counters")
var result = counterCol.FindAndModify(new FindAndModifyArgs()
{
Query = Query.EQ(d => d.Id, "orderId"),
Update = Update.Inc(d => d.Value, 1),
VersionReturned = FindAndModifyDocumentVersion.Modified,
Upsert = true, //Create if the document does not exists
});
Использование нового драйвера v2.x:
public class Sequence
{
[BsonId]
public ObjectId _Id { get; set; }
public string Name { get; set; }
public long Value { get; set; }
public void Insert(IMongoDatabase database)
{
var collection = database.GetCollection<Sequence>("sequence");
collection.InsertOne(this);
}
internal static long GetNextSequenceValue(string sequenceName, IMongoDatabase database)
{
var collection = database.GetCollection<Sequence>("sequence");
var filter = Builders<Sequence>.Filter.Eq(a => a.Name, sequenceName);
var update = Builders<Sequence>.Update.Inc(a => a.Value, 1);
var sequence = collection.FindOneAndUpdate(filter, update);
return sequence.Value;
}
}