Mongo C# Driver: Deserialize BsonValue

前端 未结 4 1073
忘掉有多难
忘掉有多难 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:31

    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 Dimensions{ get; set; }
    
    }
    
    var product = srv["db"]["products"].FindOneByIdAs();
    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();
    foreach (BsonValue value in dimensionsVal)
    {
      var bsonDoc = (BsonDocument) value;
      var d = new Dimension();
      d.Height = bsonDoc["Height"];
      d.Width = bsonDoc["Width"];
      list.Add(d);
    }
    

提交回复
热议问题