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.
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.
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.
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.
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()));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With