How to do an upsert with MongoDB 2.0? How to do an upsert with MongoDB 2.0? mongodb mongodb

How to do an upsert with MongoDB 2.0?


Pass an instance of UpdateOptions as the options parameter in UpdateOneAsync(filter, update, options), e.g.:

collection.UpdateOneAsync(p => p.Id == user.Id,     Builders<User>.Update.Set(p => p.Name, "John"),     new UpdateOptions { IsUpsert = true });

EDIT

To replace the document, call ReplaceOneAsync instead:

collection.ReplaceOneAsync(p => p.Id == user.Id,     user,     new ReplaceOptions { IsUpsert = true });