Yes, String
C# 对象中的属性有Int32
mongo 存储中的值,因此在序列化期间会出现异常(请参阅代码MongoDB.Bson.Serialization.Serializers.BsonStringSerializer https://github.com/mongodb/mongo-csharp-driver/blob/a7fbdb3b60208118529f05e69f2b58e61eda66d8/MongoDB.Bson/Serialization/Serializers/BsonStringSerializer.cs class).
1)您可以定义自己的序列化器,它将反序列化Int32
字符串属性的值以及String
那些。这里是:
public sealed class StringOrInt32Serializer : BsonBaseSerializer
{
public override object Deserialize(BsonReader bsonReader, Type nominalType,
Type actualType, IBsonSerializationOptions options)
{
var bsonType = bsonReader.CurrentBsonType;
switch (bsonType)
{
case BsonType.Null:
bsonReader.ReadNull();
return null;
case BsonType.String:
return bsonReader.ReadString();
case BsonType.Int32:
return bsonReader.ReadInt32().ToString(CultureInfo.InvariantCulture);
default:
var message = string.Format("Cannot deserialize BsonString or BsonInt32 from BsonType {0}.", bsonType);
throw new BsonSerializationException(message);
}
}
public override void Serialize(BsonWriter bsonWriter, Type nominalType,
object value, IBsonSerializationOptions options)
{
if (value != null)
{
bsonWriter.WriteString(value.ToString());
}
else
{
bsonWriter.WriteNull();
}
}
}
然后用这个序列化器标记必要的属性(您认为在 MongoDB 中具有不同的类型),例如:
[BsonElement("Body")]
[BsonSerializer(typeof(StringOrInt32Serializer))]
public string Body { get; set; }
我也在这里发现了非常相似的问题:使用 MongoDb csharp 驱动程序更改类型时反序列化字段 https://stackoverflow.com/questions/10126025/deserializing-field-when-type-is-changed-using-mongodb-csharp-driver
2)第二种方法 - 是“正常化”存储中的数据:将所有整数字段值转换为字符串。所以,你应该改变领域$type
从 16(32 位整数)到 2(字符串)。看BSON类型 http://docs.mongodb.org/manual/reference/bson-types/。让我们这样做是为了body
field:
db.train.find({ 'body' : { $type : 16 } }).forEach(function (element) {
element.body = "" + element.body; // Convert field to string
db.train.save(element);
});