【问题标题】:Upsert a complete document (replace all if "Id" exists // insert if "Id" doesn't exists ) with C# Driver (MongoDB)使用 C# 驱动程序 (MongoDB) 插入一个完整的文档(如果“Id”存在则全部替换 // 如果“Id”不存在则插入)
【发布时间】: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 是否存在存在在数据库中插入新文档。

【问题讨论】:

    标签: c# mongodb driver upsert


    【解决方案1】:

    理想情况下,您只需为要设置的每个属性调用Builders&lt;YourClass&gt;.Update.Set()。但是,由于您已将其设为通用,而我个人会尽量避免,您可以通过构建自己的 BsonDocument 来表示更新操作:

    public static async Task UpsertDocumentByGuid<T>(string table, string guid, T document)
    {
        var client = new MongoClient();
        var database = client.GetDatabase("test");
        var collection = database.GetCollection<T>(table);
        var filter = new BsonDocument("Id", guid);
    
        var bsonDocument = document.ToBsonDocument();
        bsonDocument.Remove("_id");
        var update = new BsonDocument()
        {
            {"$set", bsonDocument}
        };
    
        var options = new UpdateOptions { IsUpsert = true };
    
        var result = await collection.UpdateOneAsync(filter, update, options);
    }
    

    【讨论】:

      猜你喜欢
      • 2017-02-10
      • 1970-01-01
      • 1970-01-01
      • 2011-02-17
      • 2018-09-17
      • 2021-10-03
      • 2016-08-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多