【发布时间】:2020-07-09 10:42:48
【问题描述】:
我很难在 MongoDB 中进行 Upsert。我想完成这种行为:
创建要上传到数据库的对象(NachName=LastName // VorName=FirstName): 类定义
public class NameModel
{
[BsonId]
public Guid Id { get; set; }
public string NachName { get; set; }
public string VorName { get; set; }
public NameModel()
{
NachName = "Mustermann";
VorName = "Max";
}
public NameModel(string nachName, string vorName)
{
NachName = nachName;
VorName = vorName;
}
}
查看数据库是否已经有一个具有给定 Guid (Filter = Guid) 的条目(文档)。调用方法:
NameModel name = new NameModel();
DB.UpsertDocumentByGuid<NameModel>("NameCollection", TxbGuid.Text, name);
这是被调用的 Methode,这是错误
public void UpsertDocumentByGuid<T>(string table, string guid, T document)
{
var collection = db.GetCollection<T>(table);
var filter = new BsonDocument("Id", guid);
var update = document ; // ERROR -> converting T to MongoDB.Driver.UpdateDefinition<T> not possible
var options = new UpdateOptions { IsUpsert = true };
var result = collection.UpdateOne(filter, update, options);
}
我想要一个方法来查看 Guid 是否已经存在,如果是,则更新文档中的不同之处(将提供给 Methode 的文档与找到的 Guid 的文档进行比较)或者 Guid 是否存在存在在数据库中插入新文档。
【问题讨论】: