karthick
karthick

Reputation: 6158

How to get the count of the sub-document object - mongoDB

I am having following documentsample in 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
           }
    }
  }
  ]
}

Requirement:

Have to find out the count of the Qty object.

Expected result:

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

Is it possible to get the object size?

Any suggestion will be helpful.

Upvotes: 3

Views: 146

Answers (2)

Malcolm Murdoch
Malcolm Murdoch

Reputation: 1085

Definitely better to change the schema, but you should be able to mapReduce yourself out of pain:

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)

This should give you a new collection called qtycounts with the 'Type' set as the _id and the qtycounts in 'value.QtyCount' (something Mongodb always does to confuse people).

Upvotes: 0

xlembouras
xlembouras

Reputation: 8295

I think you should reconsider your schema. If you can change the Qty to an array and add the date to a date field it would 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 would be able to use indexes effectively and the aggregation framework to do your counts.

If that is not an option I would suggest aggregating that data on an extra field, and updating that field on insert / update.

Upvotes: 3

Related Questions