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

JalapenoHottie picture JalapenoHottie · Apr 3, 2012 · Viewed 14.6k times · Source

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.

Answer

JustinN picture JustinN · Aug 22, 2012

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()));