Mongo C# Driver: Deserialize BsonValue

前端 未结 4 1071
忘掉有多难
忘掉有多难 2021-02-05 15:42

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

{
  \"_id\": \"abcdef01234\",
  \"Name\": \"Product A\",
  \"Dimensions\": [
    {
      \"Heigh         


        
4条回答
  •  长情又很酷
    2021-02-05 16:27

    I would declare your class with a Dimensions property of type List 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 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).

提交回复
热议问题