Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongodb c# API V2: Difference between ReplaceOne and FindOneAndReplace

Looking a the mongodb documentation I read that FindOneAndReplace would be an ATOMIC operation. But what I don't understand is why ReplaceOne wouldn't be atomic? And if there is a difference why should one use ReplaceOne at all?

like image 703
Thomas Avatar asked Apr 27 '16 16:04

Thomas


1 Answers

The documentation unveils a different method signature:

ReplaceOne:

ReplaceOneResult ReplaceOne(
    FilterDefinition<TDocument> filter,
    TDocument replacement,
    ReplaceOptions options = null,
    CancellationToken cancellationToken = null
)

FindOneAndReplace:

TProjection FindOneAndReplace<TProjection>(
    FilterDefinition<TDocument> filter,
    TDocument replacement,
    FindOneAndReplaceOptions<TDocument, TProjection> options = null,
    CancellationToken cancellationToken = null
)

Most notably the return type and the options parameter differ.

While ReplaceOne returns a ReplaceOneResult, FindOneAndReplace returns a document (be aware of the ReturnDocument property in the options).

The ReplaceOptions are rather limited compared to FindOneAndReplaceOptions, e.g. the former does not provide a sort property to give you control over which document will be the first of the matching documents in the collection. This doesn't matter if you filter based on an ID, but if you want to replace the latest document the sort option is very useful.

(Side note: I personally find the documentation here https://docs.mongodb.com/manual/reference/method/db.collection.replaceOne/ and here https://docs.mongodb.com/manual/reference/method/db.collection.findOneAndReplace/ much more helpful, as they explain the usage in more detail and also provide some examples. But I don't know how closely it matches the MongoDB C# driver.)

like image 172
Elias Rabl Avatar answered Sep 19 '22 20:09

Elias Rabl