findAndModify return WriteResult

I do query with logic “insert if not exists”. How i can check was upsert or return exists document ?

 var u = Builders<Blog>.Update
                .SetOnInsert(f => f.BlogId, blogId)
                .SetOnInsert(f => f.VideoId, videoId)
                -- other fields...

var blog = Blog.FindOneAndUpdate<Blog>(c => c.BlogId == blogId && c.VideoId == VideoId, u, 
   new FindOneAndUpdateOptions<Blog>{IsUpsert = true, ReturnDocument = ReturnDocument.After}
);

bool wasUpsert =  ? 
return wasUpsert;

Hi @alexov_inbox,

You didn’t specify so I’m guessing your using C# from the syntax?

The ReturnDocument option provides two options, Before and After (see also, properties). You’ve specified After, which means you’ll always get the document you inserted when performing an upsert. Using the value Before will return a null if the document did not previously exist. This does complicate getting the final document should an upsert occur, but I’m guessing you already have a Blog object hanging around somewhere and it should be fairly straight forward to check if blog == null and set the values for BlogId and VideoId.

Thanks,

Justin

1 Like

its good use Before and check to null. But i need get After(final) document. In your variant i should use second query

  1. var blog = (query with ReturnDocument = ReturnDocument.Before)
  2. var finalBlog = (query get by id)

bool wasUpsert = blog == null;
var blog = finalBlog;