Upserting in Mongo DB using official C# driver

后端 未结 4 771
别跟我提以往
别跟我提以往 2020-12-04 18:04

In the official documentation of mongodb they mention upserts, so it would be really nice to write an upsert command instead of:

if (_campaignRepo.Exists(cam         


        
4条回答
  •  感动是毒
    2020-12-04 18:37

    Starting from v2.0 of the driver there's a new async-only API. The old API should no longer be used as it's a blocking facade over the new API and is deprecated.

    The currently recommended way to upsert a document is by calling and awaiting ReplaceOneAsync with the IsUpsert flag turned on and a filter that matches the relevant document:

    Hamster hamster = ...
    var replaceOneResult = await collection.ReplaceOneAsync(
        doc => doc.Id == hamster.Id, 
        hamster, 
        new UpdateOptions {IsUpsert = true});
    

    You can check whether the operation was an insert or an update by looking at ReplaceOneResult.MatchedCount:

提交回复
热议问题