c# - 使用官方 C# 驱动程序在 Mongo DB 中进行更新插入

在 mongodb 的官方文档中,他们提到了 upserts,所以写一个 upsert 命令而不是:

if (_campaignRepo.Exists(camp))
{
    _campaignRepo.DeleteByIdAndSystemId(camp);
}

_campaignRepo.Save(camp);

如果可能的话,可以在数据库级别实现该逻辑的东西。那么如果有一个 upsert 的方法是什么?

最佳答案

版本 2 的 MongoDB C# 驱动程序需要在写入命令中设置 IsUpsert 标志。此示例将 upsert 整个文档。

var newDoc = new BsonDocument { { "_id", 123 }, { "someKey", "someValue" } };
var result = await collection.ReplaceOneAsync(
                filter: new BsonDocument("_id", 123),
                options: new ReplaceOptions { IsUpsert = true },
                replacement: newDoc);

版本 1 的 MongoDB C# 驱动程序在 Save 命令中实现此逻辑。

var newDoc = new BsonDocument { { "_id", 123 }, { "someKey", "someValue" } };
collection.Save(newDoc);

The Save method is a combination of Insert and Update. If the Id member of the document has a value, then it is assumed to be an existing document and Save calls Update on the document (setting the Upsert flag just in case it actually is a new document after all). Otherwise it is assumed to be a new document and Save calls Insert after first assigning a newly generated unique value to the Id member.

引用:http://mongodb.github.io/mongo-csharp-driver/1.11/driver/#save-tdocument-method

注意:但这确实需要正确映射 Id 字段。更多信息:http://mongodb.github.io/mongo-csharp-driver/1.11/serialization/#identifying-the-id-field-or-property

https://stackoverflow.com/questions/7240028/

相关文章:

arrays - 查询 MongoDB 以匹配数组中的第一项

mongodb - 如何通过一次调用将一组对象推送到 Mongoose 中的数组中?

mongodb - 插入后如何在 PyMongo 中获取对象 ID?

session - node.js + express.js : session handling

mongodb - 执行 mongoexport 时 "too many positional op

mongodb - 如何从 MongoDB 中删除 system.profile 集合?

mongodb - 如何停止在 mongodb 集合中插入重复文档

node.js - Mongoose 密码哈希

c# - 如何使用 MongoDB 的 C# 驱动程序指定 Order 或 Sort?

python - 从字符串中删除每个非 utf-8 符号