Mongo: Query to get count of objects in a nested field.

1,074 views
Skip to first unread message

Karan

unread,
Aug 12, 2013, 5:51:45 AM8/12/13
to mongod...@googlegroups.com
Hello Everyone,

I needed some help to create a count query on nested objects in a field, across all documents. Each document json has a many fields. One particular field called "hotlinks" comprises of many internal dynamic object fields.
Doc1:
{
  hotlinks : { 112222:{....} , 333333: {.....} , 545555: {.....}      }
}

Doc2:
{
  hotlinks : { 67756:{....} , 756767: {.....} , 1111111: {.....}      }
}

Each document has a hotlinks fields. The hotlinks field comprises of varied inner hotlink objects. Each key is a java unique id and has objects that contain data (inner fields)
I needed a way to get the count of all the inner nested objects of the field – ‘hotlinks’.
For example the summation of inner objects of hotlinks in doc1 and doc2 would be 6.
Is there any way to do this via a single query to get the count across all documents.

Thanks a lot,
Karan

Gary R

unread,
Aug 13, 2013, 1:45:08 PM8/13/13
to mongod...@googlegroups.com
A few thoughts.
  • This would work nicely in the aggregation framework if the 'hotlinks fields" would be elements in an array instead of a document.
  • Or, you could easy maintain a counter as hotlinks are added and removed and just read this.
  • Or, in map-reduce, javascript could include the idea:  for(k in obj) {count++;}
Gary R.

--------------------------------

Karan

unread,
Aug 14, 2013, 5:21:16 AM8/14/13
to mongod...@googlegroups.com
Hi Gary,

Thank you so much. All the ideas you gave are great.
For now, i have implemented the second option that you have suggested- Maintain a counter.
This is now working for me.

Thanks so much,
Karan
Reply all
Reply to author
Forward
0 new messages