Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 759
JalapenoHottie Avatar asked Apr 03 '12 00:04

JalapenoHottie


People also ask

What is Mongo C?

The MongoDB C Driver, also known as “libmongoc”, is a library for using MongoDB from C applications, and for writing MongoDB drivers in higher-level languages. It depends on libbson to generate and parse BSON documents, the native data format of MongoDB.

What is a Mongo Driver?

The official MongoDB Node. js driver allows Node. js applications to connect to MongoDB and work with data. The driver features an asynchronous API which allows you to interact with MongoDB using Promises or via traditional callbacks.

What is Mongo shell?

The mongo shell is an interactive JavaScript interface to MongoDB. You can use the mongo shell to query and update data as well as perform administrative operations.


1 Answers

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()));
like image 90
JustinN Avatar answered Sep 22 '22 03:09

JustinN