Update List<string> in mongoDB

房东的猫 提交于 2019-12-24 19:43:03

问题


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


回答1:


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



回答2:


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



回答3:


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


来源:https://stackoverflow.com/questions/11618427/update-liststring-in-mongodb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!