MongoDB Map Property 'new' in findAndModify using FindOneAndUpdateOptions class C# Driver

2.1k views Asked by At

I'm trying to implement a getNextSequence function for mongoDB explain on this Link I'm using the lattes C# driver but I not sure how to map the new : true property in the FindOneAndUpdateOptions

MongoDB Code

function getNextSequence(name) {
   var ret = db.counters.findAndModify(
          {
            query: { _id: name },
            update: { $inc: { seq: 1 } },
            new: true,
            upsert: true
          }
   );

   return ret.seq;
}

C# Code

    public async Task<long> GetNextObjectSequenceAsync(string objectName)
    {
        var collection = this.Context.GetCollection<ObjectSequence>("Counters");
        var filter = new FilterDefinitionBuilder<ObjectSequence>().Where(x => x.Name == objectName);
        var options = new FindOneAndUpdateOptions<ObjectSequence, ObjectSequence>() { IsUpsert = true };
        var update = new UpdateDefinitionBuilder<ObjectSequence>().Inc(x => x.Sequence, 1);

        ObjectSequence seq = await collection.FindOneAndUpdateAsync<ObjectSequence>(filter, update, options);

        return seq.Sequence;

    }
1

There are 1 answers

0
rnofenko On BEST ANSWER

FindOneAndUpdateOptions has ReturnDocument enum where

ReturnDocument.Before = 'new':false

ReturnDocument.After = 'new':true

In your case options should be:

var options = new FindOneAndUpdateOptions<ObjectSequence, ObjectSequence>() { ReturnDocument = ReturnDocument.After, IsUpsert = true };