2011-08-07 54 views
6

在嘗試向Mongo中的現有文檔中添加複雜類型時遇到問題。向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」:{ 「數據」: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:無法確定實際噸 YPE對象的反序列化NominalType是System.Object的和BsonType是解決的文 ENT。)。

與data3不同,data2沒有鑑別器。我在做什麼?

回答

4

好吧,如果司機想鑑別你可以通過鑄造類的更新對象給它:

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

這將解決您的問題。

BTW,您的更新沒有真正內UserObjects更新數據2域,它的文檔中創建新的數據2域,下面的代碼應能正常工作:

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

解串器無法根據Bson表示自己弄清楚它應該使用哪種類型。前幾天看看我的問題。我認爲它澄清了一些事情。實現BsonSerializable可以解決問題。

Storing composite/nested object graph