蒙戈C#驱动程序:反序列化BsonValue [英] Mongo C# Driver: Deserialize BsonValue

查看:183
本文介绍了蒙戈C#驱动程序:反序列化BsonValue的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在MongoDB中的文档的结构类似于这样:

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; }
}



我选择以这种方式产品A的文件:

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"];

现在我有一个名为dimensionsVal BsonValue它的类型是BsonArray的。我真正想要的是一个List<尺寸取代。如何转换dimensionsVal到List<尺寸>

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>?

修改
尺寸类实际上是比显著更复杂的我描述。我想保持独立的尺寸从产品,因为内存的担忧。我想保持产品在内存中,但尺寸不是(潜在的巨大)名单。出于这个原因,我不希望有一个List作为产品类的属性。

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.

推荐答案

下面是怎么了可以做到:

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());

这篇关于蒙戈C#驱动程序:反序列化BsonValue的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆