aggregation count subdocument length

2,312 views
Skip to first unread message

Raitucarp

unread,
Jun 5, 2013, 1:34:38 PM6/5/13
to mongod...@googlegroups.com
I have documents like this:
{
    _id: 030341,
    title: "this is title',
   content: "this is content",
   comments:[
        {name: 'baba', content: 'very long comments', _id: 'beX23', postedAt: ....},
        {name: 'rere', content: 'very big data', _id: 'beX24', postedAt: ....},
        .........
  ]
}

How to use aggregation to count comments length? I want the result have such this:

{
   title: 'title',
   content: 'the content'
   commentCount: 5
}, .....



Jeff Lee

unread,
Jun 5, 2013, 2:06:18 PM6/5/13
to mongod...@googlegroups.com
I believe you need to unwind the array:

e.g.

db.posts.aggregate(
{ $unwind: '$comments'},
{ $group: { _id:{ title:'$title', content:'$content'}, thecount:{$sum:1}}}
) ;

I would probably store the count in the top level document though...it will probably be cheaper in the long run.






--
--
You received this message because you are subscribed to the Google
Groups "mongodb-user" group.
To post to this group, send email to mongod...@googlegroups.com
To unsubscribe from this group, send email to
mongodb-user...@googlegroups.com
See also the IRC channel -- freenode.net#mongodb
 
---
You received this message because you are subscribed to the Google Groups "mongodb-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email to mongodb-user...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

Raitucarp

unread,
Jun 5, 2013, 2:30:53 PM6/5/13
to mongod...@googlegroups.com
Oh Okay, I see, the title and the content, is in _id.. Yeah this is the solution. Thanks jeffl

I would probably store the count in the top level document though...it will probably be cheaper in the long run.

What do you mean? $inc comments_count every I push new comment? Could you give me an insight about that?

Jeff Lee

unread,
Jun 5, 2013, 6:10:12 PM6/5/13
to mongod...@googlegroups.com
Yup.  Your mileage may vary since you can get the counts using aggregation instead of map-reduce.

Also, just noticed that the query I posted assumes that title/content are unique.  You may have to tweak that if it's not the case.

Regards.



--
Reply all
Reply to author
Forward
0 new messages