Re: Aggregation framework. Group by sub-document fields

2,407 views
Skip to first unread message

kirill kazachenko

unread,
Nov 13, 2012, 4:22:30 PM11/13/12
to mongod...@googlegroups.com
for example, guide at page

how to group authors in subset comments, and get count of their comments?

{
 title : "this is my title" ,
 author : "bob" ,
 posted : new Date () ,
 pageViews : 5 ,
 tags : [ "fun" , "good" , "fun" ] ,
 comments : [
             { author :"joe" , text : "this is cool" } ,
             { author :"sam" , text : "this is bad" }
 ],
 other : { foo : 5 }
}

Stephen Lee

unread,
Nov 14, 2012, 12:12:45 PM11/14/12
to mongod...@googlegroups.com
Hi Kirill,

Check out the $unwind operator which will take the documents in your aggregation pipeline and multiplexes the array entries as separate documents, eg.

Before $unwind:

{
a: 1,
b: [ 2,3,4]
}

After $unwind:

{ a:1,b:2 },
{ a:1,b:3 },
{ a:1,b:4 }

After you include the $unwind in your pipeline, add the $group operation on "$events.name".

-Stephen

On Tuesday, November 13, 2012 4:13:35 PM UTC-5, kirill kazachenko wrote:
Hello, i have a question about grouping by sub elements.

i have next structure:
{
"name":"name",
"events": [
     {"name":"event1", "date": ...},
     {"name":"event2", "date": ...}
  ]
}

I'm need to extract and group all events by name with it's count, how can i do this with the aggregation?

db.sessions.aggregate([{$group: {_id:"$events.name"}}])

i have response:

{
        "result" : [
                {
                        "_id" : [ ]
                },
                {
                        "_id" : [
                                "open_home",
                                "open_home",
                                "open_homdfe",
                                "open_homdfe",
                                "4en_homdfe",
                                "4en_homdfe"
                        ]
                }
        ],
        "ok" : 1
}

kirill kazachenko

unread,
Nov 15, 2012, 1:46:06 AM11/15/12
to mongod...@googlegroups.com
WOW! Really thanks! It's that what i was need!

> db.sessions.aggregate(
{$project: {_id:1,events:1}},
{$unwind:"$events"},
{$group: {_id:"$events.name", count: {$sum:1}}})


made:


{
        "result" : [
                {
                        "_id" : "4en_homdfe",
                        "count" : 2
                },
                {
                        "_id" : "open_homdfe",
                        "count" : 2
                },
                {
                        "_id" : "open_home",
                        "count" : 2
                }
        ],
        "ok" : 1
}

среда, 14 ноября 2012 г., 20:12:45 UTC+3 пользователь Stephen Lee написал:
Reply all
Reply to author
Forward
0 new messages