0

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?

3
  • You can use the aggregation framework: db.col.aggregate([{$group: {_id: '$publish_target', value: {$sum: 1} }}]) Easy enough to translate to PHP that one is Commented Feb 5, 2013 at 17:26
  • Tried: $collection = $this->mongoDB->Post; $out = $collection->aggregate(array('$group' => array('_id' => '$publish_target', 'value' => array('$sum' => 1)))); The output wasnt great. array(3) { 'errmsg' => string(11) "no such cmd" 'bad cmd' => array(2) { 'aggregate' => string(4) "Post" 'pipeline' => array(1) { '$group' => array(2) { ... } } } 'ok' => double(0) } Commented Feb 5, 2013 at 17:33
  • Hmm you might running an old mongodb version if it says there is not aggregate command, in which as anh said it is because you didn't put true there Commented Feb 5, 2013 at 17:36

1 Answer 1

1

I'm not sure if this is the issue, but comparing with my own code this line

$keys = array('publish_target');

should look like this

$keys = array('publish_target' => true);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.