簡體   English   中英

使用 C# 驅動程序(MongoDB)更新完整文檔(如果“Id”存在則替換所有文檔//如果“Id”不存在則插入)

[英]Upsert a complete document (replace all if "Id" exists // insert if "Id" doesn't exists ) with C# Driver (MongoDB)

我很難在 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(過濾器 = Guid)的條目(文檔)。 調用方法:

NameModel name = new NameModel();
DB.UpsertDocumentByGuid<NameModel>("NameCollection", TxbGuid.Text, name);

這是被調用的方法,這是錯誤

        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 不存在,請插入數據庫中的新文檔。

理想情況下,您只需為要設置的每個屬性調用Builders<YourClass>.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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM