Reputation: 3137
I have an aggregate to pull metrics from a collection of "share" actions. These metrics are grouped by day and the platform(twitter, pintrest, etc). Each stage works fine except when it comes to formatting the output in a $project
stage, I cannot seem to get the platform
string to project in my output. I see it in the _id still, however I cannot get it to project to the other field.
The aggregation is as follows:
{
$unwind: "$platforms"
},
{
$project: {
day: {$dayOfMonth: "$created_at"},
month: {$month: "$created_at"},
year: {$year: "$created_at"},
platforms: 1
}
},
{
$group: {
_id: {
platorms: "$platforms",
day: "$day",
month: "$month",
year: "$year"
},
count: {$sum: 1}
}
},
{
$project: {
day: "$_id.day",
month: "$_id.month",
year: "$_id.year",
platform: "$_id.platforms",
count: 1
}
}
The output of the following is:
{
"result" : [
{
"_id" : {
"platorms" : "EMAIL",
"day" : 28,
"month" : 4,
"year" : 2015
},
"count" : 1,
"day" : 28,
"month" : 4,
"year" : 2015
},
{
"_id" : {
"platorms" : "EMAIL",
"day" : 27,
"month" : 4,
"year" : 2015
},
"count" : 10,
"day" : 27,
"month" : 4,
"year" : 2015
},
{
"_id" : {
"platorms" : "SMS",
"day" : 27,
"month" : 4,
"year" : 2015
},
"count" : 1,
"day" : 27,
"month" : 4,
"year" : 2015
},
{
"_id" : {
"platorms" : "FACEBOOK",
"day" : 27,
"month" : 4,
"year" : 2015
},
"count" : 1,
"day" : 27,
"month" : 4,
"year" : 2015
}, ...
The integers for day, month, and year project fine, however platforms does not.
Upvotes: 0
Views: 137
Reputation: 61293
This is because in your $group
stage you have compound _id
with platorms: "$platforms"
(missing f
in field name) and you are projecting the $_id.platforms
in your last $project
stage and since such field doesn't exist you will not get any result. You can also exclude the _id
field using _id: 0
.
Change your $group
stage to:
{
$group: {
_id: {
platforms: "$platforms",
day: "$day",
month: "$month",
year: "$year"
},
count: {$sum: 1}
}
}
Upvotes: 1