我需要按 _id 和国家/地区分组。我已经设法分组_id
,但想知道如何对这些国家/地区进行分组_id
并返回每个国家/地区的计数。
我正在使用聚合框架。到现在为止还挺好。
conn = Mongo::Connection.new
db = conn['foobar_development']
cmd = {
aggregate: 'live_daily_stats',
pipeline: [
{ '$project' => {
:metacontent => 1,
:visits => 1,
} },
{ '$unwind' => '$visits' },
{ '$match' => { 'visits.minute' => { '$gt' => 224 } } },
{ '$sort' => { 'visits.minute' => 1 } },
{ '$group' => {
:_id => '$_id',
:visits => { '$push' => '$visits' },
:visits_count => { '$sum' => 1 },
:metacontent => { '$addToSet' => '$metacontent' },
}
},
{ '$sort' => { 'visits_count' => -1 } },
]
}
res = db.command(cmd)['result']
以下返回:
[
[0] {
"_id" => "20120726/foobar/song/custom-cred",
"visits" => [
[0] {
"country_name" => "UK",
"iso_two_letter_country_code" => "UK",
"referer" => "http://localhost:3000/",
"minute" => 59,
"token_id" => "134326199711wfryhpdq"
},
[1] {
"country_name" => "UK",
"iso_two_letter_country_code" => "UK",
"referer" => "http://localhost:3000/",
"minute" => 59,
"token_id" => "134326199711wfryhpdq"
},
[2] {
"country_name" => "US",
"iso_two_letter_country_code" => "US",
"referer" => "http://localhost:3000/",
"minute" => 59,
"token_id" => "134326199711wfryhpdq"
}
],
"visits_count" => 1,
"metacontent" => [
[0] {
"date" => "20120726"
}
]
},
[1] {
"_id" => "20120725/foobar/song/test-pg3-long-title-here-test-lorem-ipsum-dolor-lo",
"visits" => [
[0] {
"country_name" => "UK",
"iso_two_letter_country_code" => "UK",
"referer" => "http://localhost:3000/",
"minute" => 58,
"token_id" => "13432600883knjzcbic"
}
],
"visits_count" => 1,
"metacontent" => [
[0] {
"date" => "20120725"
}
]
}
]