Mongo C# Driver: Deserialize BsonValue

Joel Harris picture Joel Harris · Jul 15, 2011 · Viewed 30.8k times · Source

I have a document in mongodb that is structured similar to this:

{
  "_id": "abcdef01234",
  "Name": "Product A",
  "Dimensions": [
    {
      "Height": 32,
      "Width": 64
    },
    {
      "Height": 16,
      "Width": 32
    },
    {
      "Height": 8,
      "Width": 16
    }
  ]
}

I also have a class defined to represent dimensions (the sub document from above)

public class Dimension
{
  public int Height { get; set; }
  public int Width { get; set; }
}

I am selecting the "Product A" document in this manner:

MongoServer srv = MongoServer.Create(myConnStr);
BsonDocument doc = srv["db"]["products"].FindOneById(ObjectId.Parse("abcdef01234"));
BsonValue dimensionsVal = doc["Dimensions"];

Now I have a BsonValue named dimensionsVal which is of type BsonArray. What I really want is a List<Dimension>. How do I convert dimensionsVal to a List<Dimension>?

Edit The dimension class is actually significantly more complex than what I described. I want to keep the Dimensions separate from the Product because of memory concerns. I want to keep the Product in memory, but not the (potentially enormous) list of dimensions. For this reason, I don't want to have a List as a property of the Product class.

Answer

Joel Harris picture Joel Harris · Jul 15, 2011

Here is how it can be done:

using MongoDB.Bson.Serialization;

MongoServer srv = MongoServer.Create(myConnStr);
BsonDocument doc = srv["db"]["products"].FindOneById(ObjectId.Parse("abcdef01234"));
BsonValue dimVal = doc["Dimensions"];
List<Dimension> d = BsonSerializer.Deserialize<List<Dimension>>(dimVal.ToJson());