简体   繁体   中英

Update List<string> in mongoDB

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM