使用mongo C#驱动程序,如何序列化自定义对象数组以便存储它?

Jal*_*tie 13 c# mongodb mongodb-.net-driver

我有一个包含一系列文档的产品文档.例如

{
 id: 1,
 name: "J-E-L-L-O",
 store:[{id: 1,
    name: "Store X"},
    {id: 2,
    name: "Store Y"}]
}
Run Code Online (Sandbox Code Playgroud)

我想将"Store Y"的名称更改为"Store Z",例如.当时,我不知道对象的索引.所以,我拉出整个数组,找到要更新的对象,更改名称,然后尝试使用更新的数组设置"store"的值.

productCollection.Update(query, Update.Set("store", storeList.ToBsonDocument()));
Run Code Online (Sandbox Code Playgroud)

但是,我收到一个错误: "An Array value cannot be written to the root level of a BSON document."

我想我只需要知道如何将自定义对象数组序列化为BsonDocuments数组.

在此先感谢您的帮助.

Jus*_*inN 7

不幸的是我遇到了同样的问题,并最终制作了一个扩展方法来帮助我解决它.

    public static BsonArray ToBsonDocumentArray(this IEnumerable list)
    {
        var array = new BsonArray();
        foreach (var item in list)
        {
            array.Add(item.ToBson());
        }
        return array;
    }
Run Code Online (Sandbox Code Playgroud)

所以你应该能够做到:

productCollection.Update(query, Update.Set("store", storeList.ToBsonDocumentArray()));
Run Code Online (Sandbox Code Playgroud)


Gat*_* VP 2

异常表明您无法将数组/列表转换为 BsonDocument。我认为您正在寻求转换storeList[BsonArray][1].

如果storeList已经是一个数组BsonDocument或某些IEnumerable<T>地方可以转换为 a ,则您根本BsonDocument不需要转换该变量。storeList