Using the mongo C# driver, how to serialize an array of custom object in order to store it?

吃可爱长大的小学妹 提交于 2019-12-23 07:01:59

问题


I have a product document that contains an array of documents. For example

{
 id: 1,
 name: "J-E-L-L-O",
 store:[{id: 1,
    name: "Store X"},
    {id: 2,
    name: "Store Y"}]
}

I would like to change the name of "Store Y" to Store Z", for instance. At the time, I don't know the index of the object. So, I pull the entire array, find the object to update, change the name, and then attempt to set the value of "store" with the updated array.

productCollection.Update(query, Update.Set("store", storeList.ToBsonDocument()));

However, I am getting an error: "An Array value cannot be written to the root level of a BSON document."

I think I just need to know how to serialize the array of custom objects to an array of BsonDocuments.

Thanks in advance for your help.


回答1:


Unfortunately I had the same problem and ended up making an extension method to help me get around it.

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

so you should be able to do:

productCollection.Update(query, Update.Set("store", storeList.ToBsonDocumentArray()));



回答2:


The exception says that you cannot convert an array/list into a BsonDocument. I think that you are looking to convert storeList to a [BsonArray][1].

If storeList is already an array of BsonDocument or some IEnumerable<T> where to can be converted to a BsonDocument, the you should not need to cast the storeList variable at all.




回答3:


you should use

BsonDocument.Parse(storeList);

instead of

storeList.ToBsonDocument()



回答4:


Little edit for the accepted answer function:

public static BsonArray ToBsonDocumentArray(this IEnumerable list)
    {
        var array = new BsonArray();
        foreach (var item in list)
        {
            array.Add(item);
        }
        return array;
    }

we don't need to convert item.ToBson(). There is already an implicit conversion from string to bson.Thats the reason i was getting an error message "A String value cannot be written to the root level of a BSON document."



来源:https://stackoverflow.com/questions/9985509/using-the-mongo-c-sharp-driver-how-to-serialize-an-array-of-custom-object-in-or

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!