我在尝试将复杂类型添加到Mongo中的现有文档时遇到了麻烦.
我有以下两个班级.
public class UserObjectCollection { [BsonId] public Guid UserId { get; set; } public DictionaryUserObjects { get; set; } public UserObjectCollection() { UserObjects = new Dictionary (); } } public class ComplexClass { public string Bar { get; set; } public int Foo { get; set; } }
然后我创建一个新的插入对象.
var bd = new UserObjectCollection() { UserId = Guid.NewGuid(), UserObjects = { { "data", 12 }, { "data2", 123 }, { "data3", new ComplexClass() { Bar= "bar", Foo=1234 } } } };
插入文档.
mongoCollection.Insert(bd.ToBsonDocument());
我得到了结果文件.
{"_ id":BinData(3,"t089M1E1j0OFVS3YVuEDwg =="),"UserObjects":{"data":12,"data2":123,"data3":{"_ t":"ComplexClass","Bar": "bar","Foo":1234}}}
文档正确插入.然后我修改其中一个值.
var query = Query.EQ("UserObjects.data", BsonValue.Create(12)); collection.FindAndModify( query, SortBy.Null, Update.SetWrapped("data2", new ComplexClass() { Foo = -1234, Bar = "FooBar" }), returnNew: false, upsert: true);
出现在数据库中的文档.
{"UserObjects":{"data":12,"data2":{"Bar":"FooBar","Foo": - 1234},"data3":{"_ t":"ComplexClass","Bar": "bar","Foo":1234}},"_ id":BinData(3,"W11Jy + hYqE2nVfrBdxn54g ==")}
如果我尝试检索此记录,则会收到FileFormatException.
var theDocument = collection.Find(query).First();
(未处理的异常:System.IO.FileFormatException:无法确定反序列化的实际对象.NominalType是System.Object,BsonType是Docum ent.).
与data3不同,data2没有鉴别器.我在做什么?