How to get an account of a subdocument object - mongoDB

I have the following document samplein mongoDB.

 {
   "category" : [
   {
       "Type" : "one",
       "Qty" : {
           "10-Dec" : {
               "value" : 58
           },
           "11-Dec" : {
               "value" : 83
           }
       }
   },
   {
       "Type" : "two",
       "Qty" : {
           "10-Dec" : {
               "value" : 4
           },
           "11-Dec" : {
               "value" : 7
           },
           "12-Dec" : {
               "value" : 8
           }
    }
  }
  ]
}

Requirements:

Find out the number of Qty objects.

Expected Result:

Type: "one", QtyCount: 2 and Type: "Two", QtyCount: 3

Is it possible to get the size of an object?

Any suggestion would be helpful.

+3
source share
2 answers

I think you should reconsider your scheme. If you can change Qtyto an array and add a date to the field date, this will help a lot.

   {
       "Type" : "one",
       "Qty" : [
             {
               "date": "10-Dec"
               "value" : 58
             },
             {
               "date": "11-Dec"
               "value" : 83
             }
          ]
   },
   {
       "Type" : "two",
       "Qty" : [
           {
             "date": "10-Dec"
             "value" : 4
           },
             "date": "11-Dec"
             "value" : 7
           },
             "date": "12-Dec"
             "value" : 8
           }
       ]
  }

You can effectively use indexes and aggregation structure to make your bills.

If this is not an option, I would suggest combining this data into an additional field and update this field when inserting / updating.

+3

, mapReduce - :

mapper=function(){
    for (i=0;i<this.category.length;i++){
        for (q in this.category[i]['Qty']){
            emit(this.category[i]['Type'], {'QtyCount':this.category[i]['value']});
        }
    }
}

reducer=function(k,v){
    counter=0;
    for (i=0;i<v.length;i++){
        counter+=v[i].QtyCount;
    }
    return {'QtyCount':counter}
}
db.sample.mapReduce(mapper, reducer, qtycounts)

qtycounts "" _id qtycounts "value.QtyCount" (- Mongodb , ).

0

All Articles