Reputation: 9337
I have a list of strings I want to update in MongoDB using C# driver. How do I do this?
List<string> Images = someList;
var update = Update.Set("Images", Images);
collection.Update(query, update, UpdateFlags.Upsert);
this will give me an error saying that 'Images' is not BsonValue.. How do I convert string list to the bsonvalue? Thanks
Upvotes: 0
Views: 6112
Reputation: 12187
If you are using the latest 1.5 version of the C# driver you can also use the new typed Update builder and let it figure out the correct element name and how to serialize the new value.
List<string> images = someList;
var update = Update<SomeListClass>.Set(x => x.Images, images);
Upvotes: 2
Reputation: 9337
That's what I did to solve it: I converted that list to BsonArray:
List<string> Images = someList;
var update = Update.Set("Images", new BsonArray(Images));
collection.Update(query, update, UpdateFlags.Upsert);
Upvotes: 2
Reputation: 2743
It looks like Update.Set is wanting a BsonValue and you can't implicitly convert from List to BsonValue.
You look like you are doing Upserts anyway, could you use Save instead?
One way to solve this issue using Serialization and Save would be:
public class SomeListClass
{
public ObjectId id { get; set; }
public List<string> Images { get; set; }
}
SomeListClass slc = new SomeListClass();
slc.Images = someList;
collection.Save(slc);
Upvotes: 2