Reputation: 5162
Let's say this is a collection of 2 Bson documents
{
"_id": "...",
"name": "Test1",
"sub": {
"street": "134 Fake Street",
"city": "NoWhere"
}
},
{
"_id": "...",
"name": "Test2",
"sub": {
"height": "10",
"width": "20",
"sub2": {
"type": "something"
}
}
}
where the first level is a structured class but sub-levels can be completely unstructured and can have further nested documents several levels deep.
How can I deserialize this document to a C# class? All samples I have seen assume some structure in nested documents.
The following class gives an error:
public class Report
{
[BsonId]
public ObjectId _id { get; set; }
public string name { get; set; }
public BsonDocument sub { get; set; }
}
Type 'MongoDB.Bson.BsonString' with data contract name '...' is not expected. Consider using a DataContractResolver or add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.
EDIT
What I'm trying to do might be complete non-sense. Is it a better idea to just use one BsonDocument and handle everything manually without a structured class?
Upvotes: 2
Views: 3563
Reputation: 12187
I don't think the error message you are getting is from the C# driver. Can you please provide a stack trace?
I've tried to reproduce your issue but it works fine with my test program.
The document inserted by the above test program looks like this:
> db.test.find()
{ "_id" : ObjectId("5075fc6ee447ad1354c1f018"), "name" : "John Doe", "sub" : { "x" : 1, "y" : 2 } }
>
Upvotes: 3