如何使用MongoDB 2.0进行upsert?

MongoDB的界面与前一个界面完全不同。 在这里,您可以看到官方文档,其中包含有关如何搜索,插入和更新的一些示例,但有关upserts的内容呢?

meta的想法:我试图在谷歌和SO上搜索但很多资源都是指旧界面。 也许创建一个MongoLegacy标签会很好。

UpdateOptions实例作为UpdateOneAsync(filter, update, options)的options参数UpdateOneAsync(filter, update, options) ,例如:

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

编辑

要替换文档,请改为调用ReplaceOneAsync

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