MongoDB 使用 FindOneAndUpdateOptions 在 findAndModify 中映射 属性 'new' class C# 驱动程序

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

我正在尝试为 mongoDB 实现一个 getNextSequence 功能 Link I'm using the lattes C# driver but I not sure how to map the new : true property in the FindOneAndUpdateOptions

MongoDB代码

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

   return ret.seq;
}

C# 代码

    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;

    }

FindOneAndUpdateOptionsReturnDocument 枚举 where

ReturnDocument.Before = 'new':false

ReturnDocument.After = 'new':true

在您的情况下,选项应该是:

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