Search code examples
c#.netmongodbmongodb-.net-driver

MongoDb C# Driver retrieve Value of increment update


I make an update with the following inc statement to increase the value of a field

 var update = Updates.Inc(x => x.Version, 1);
 await collection.FindAndUpdateOneAsync(myQuery,update);

I want to retrieve the new (or old) value from version . Is there a built in way to do so?

Due to Transactional concerns i don't want to make a new seperate query.


Solution

  • You can try findOneAndUpdate with projection option to return document.

    To return old values

    db.collection.findOneAndUpdate(
       {},
       { $inc: { Version: 1 } },
       { projection: { Version : 1 }}
    )
    

    To return updated values, set returnNewDocument flag true

     db.collection.findOneAndUpdate(
       {},
       { $inc: { Version: 1 } },
       { projection: { Version : 1 }, returnNewDocument : true  }
     )
    

    More here https://docs.mongodb.com/manual/reference/method/db.collection.findOneAndUpdate/