【问题标题】:Adding complex classes to Mongo向 Mongo 添加复杂的类
【发布时间】:2011-08-07 11:08:41
【问题描述】:

我在尝试向 Mongo 中的现有文档添加复杂类型时遇到问题。

我有以下两个课程。

public class UserObjectCollection {

    [BsonId]
    public Guid UserId { get; set; }

    public Dictionary<string, object> UserObjects { get; set; }

    public UserObjectCollection() {
        UserObjects = new Dictionary<string, object>();
    }
}

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<ComplexClass>("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:无法确定实际 t 要反序列化的对象类型。 NominalType 是 System.Object 并且 BsonType 是 Docum 耳鼻喉科)。

与 data3 不同,data2 没有鉴别器。我在做什么?

【问题讨论】:

    标签: mongodb mongodb-.net-driver


    【解决方案1】:

    好的,如果驱动程序需要鉴别器,您可以通过将您的类转换为更新中的对象来提供它:

    (object)(new ComplexClass() { Foo = -1234, Bar = "FooBar" })
    

    这将解决您的问题。

    顺便说一句,您的更新实际上并未更新 UserObjects 中的 data2 字段,而是在文档中创建新的 data2 字段,以下代码应该可以正常工作:

     Update.SetWrapped<ComplexClass>("UserObjects.data2", 
                           new ComplexClass() { Foo = -1234, Bar = "FooBar" }),
    

    【讨论】:

      【解决方案2】:

      反序列化器无法根据 Bson 表示自行确定应该使用什么类型。看看我几天前的问题。我认为它澄清了一些事情。实施 BsonSerializable 将解决问题。

      Storing composite/nested object graph

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-11
        相关资源
        最近更新 更多