说,数据库中的现有文档是这样的:
{
"_id": "1",
"settings": {
"languages": [ "english", "french" ]
}
}
现在我想将文档更新为此:
{
"_id": "1",
"settings": {
"languages": [ "korean", "german" ]
}
}
我对以下代码感到厌倦:
var lan = new List<string> { "finish", "russian", "korean" }
collection.UpdateOne(
Builders<MyObject>.Filter.Eq("_id", "1"),
Builders<MyObject>.Update.Set("settings.languages", lan));
但是出现以下异常:
MongoDB.Bson.Serialization.Serializers.EnumerableInterfaceImplementerSerializer 2[System.Collections.Generic.List
1 [System.String],System.String]'无法转换为类型'MongoDB.Bson.Serialization.IBsonSerializer`1 [System.String] < / p>
我还尝试使用BsonArray初始化新的语言数组:
var bsonArray = new BsonArray
{
"korean",
"german"
};
collection.UpdateOne(
Builders<MyObject>.Filter.Eq("_id", "1"),
Builders<MyObject>.Update.Set("settings.languages", bsonArray));
更新可以正确执行,但是文档中的语言更改为:
{
"_id": "1",
"settings": {
"languages": "[korean, german]"
}
}
它变成"[ xx, xx ]"
,而不是[ "xx", "xx" ]
。这不是我所期望的。
答案 0 :(得分:1)
您收到该错误消息是因为您正在使用类型为MyObject
的强类型构建器,该构建器看起来或多或少如下所示:
public class MyObject
{
public string _id { get; set; }
public Settings settings { get; set; }
}
public class Settings
{
public string[] languages { get; set; }
}
因此,由于您拥有强类型的Builder
,因此由于List
和Array
之间的类型不匹配,您将获得异常。解决此问题的两种方法:
使用列表上的.ToArray()
来获得与MyObject
中相同的类型:
var lan = new List<string> { "finish", "russian", "korean" };
collection.UpdateOne(
Builders<MyObject2>.Filter.Eq("_id", "1"),
Builders<MyObject2>.Update.Set("settings.languages", lan.ToArray()));
或跳过使用BsonDocument
类的类型验证:
var collection = mydb.GetCollection<BsonDocument>("col");
var lan = new List<string> { "finish", "russian", "korean" };
collection.UpdateOne(
Builders<BsonDocument>.Filter.Eq("_id", "1"),
Builders<BsonDocument>.Update.Set("settings.languages", lan));