Im trying to group count by the field publish_target
Using MYSQL I just did:
$postsByPlatform = $db->query("SELECT COUNT(*) as `value`, `publish_target` as `key` FROM `Post` GROUP BY `publish_target` ");
$postsByPlatform = $postsByPlatform->fetchAll(PDO::FETCH_OBJ);
$return['Post']['publish_target'] = $postsByPlatform;
and got a result like this:
publish_target: [
{
value: "22",
key: "facebook"
},
{
value: "33",
key: "googleplus"
},
{
value: "44",
key: "instagram"
},
{
value: "55",
key: "other"
},
{
value: "66",
key: "twitter"
}
],
We are now converting to Mongo.
I have tried the example on PHP.net, adapted to this:
// use all fields
$keys = array('publish_target');
// set intial values
$initial = array("count" => 0);
// JavaScript function to perform
$reduce = "function (obj, prev) { prev.count++; }";
// only use documents where the "a" field is greater than 1
$g = $collection->group($keys, $initial, $reduce);
var_dump($g);
But this just returns
array(4) {
'retval' =>
array(1) {
[0] =>
array(1) {
'count' =>
double(100)
}
}
'count' =>
double(100)
'keys' =>
int(1)
'ok' =>
double(1)
}
Which means nothing to me.
How do I do this correctly?
db.col.aggregate([{$group: {_id: '$publish_target', value: {$sum: 1} }}])Easy enough to translate to PHP that one is