简体   繁体   中英

Mongo C# Driver: Deserialize BsonValue

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.

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

Try this:

public class Product
{
   [BsonId]
   public ObjectId Id { get; set; }

   public string Name{ get; set; }

   public List<DimensionDoc> Dimensions{ get; set; }
}

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

}

Product product = srv["db"]["products"].FindOneByIdAs<Product>(ObjectId.Parse("abcdef01234"));

product.Dimensions will now contain the List<> you need.

Update:

You probably looking for include/exclude functionality. In c# driver it done so:

 // load products without array of Dimensions
MongoCursorInstance.SetFields(Fields.Exclude("Dimensions"));
//load empty product with Dimensions and _id
MongoCursorInstance.SetFields(Fields.Include("Dimensions"));

Why not just create class for product? In this case driver will be able to deserialize data automatically:

class Product
{
   [BsonId]
   public ObjectId Id { get; set; }

   public string Name{ get; set; }

   public List<Dimension> Dimensions{ get; set; }

}

var product = srv["db"]["products"].FindOneByIdAs<Product>();
var dimentions = product.Dimensions;

But if you don't want create Product class you can go this way:

BsonArray dimensionsVal = doc["Dimensions"].AsBsonArray;

var list = new List<Dimension>();
foreach (BsonValue value in dimensionsVal)
{
  var bsonDoc = (BsonDocument) value;
  var d = new Dimension();
  d.Height = bsonDoc["Height"];
  d.Width = bsonDoc["Width"];
  list.Add(d);
}

I would declare your class with a Dimensions property of type List<Dimension> as others have proposed. Then if you want to read a Product without the Dimensions values write this:

ObjectId productId;
var query = Query.EQ("_id", productId);
var fields = Fields.Exclude("Dimensions");
var product = collection.Find(query).SetFields(fields).FirstOrDefault();
// product.Dimensions will be null because there was no data for it

and when you want to read the full product including all of the Dimensions write this:

ObjectId productId;
var query = Query.EQ("_id", productId);
var product = collection.FindOne(query);
// product.Dimensions will be populated this time

This will be much more efficient than reading the Dimensions into a BsonDocument and converting them to a List<Dimension> with hand-written code. That approach results in two copies of the data being loaded in memory (although presumably the BsonDocument version will be garbage collected soon thereafter if you don't keep a reference to it).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM