2

I'm trying to group by "group_name" and select fields "group_name" and "group_id" with php driver using aggregation framework:

Array
(
    [$project] => Array
        (
            [group_name] => 1
            [group_id] => 1
        )

    [$group] => Array
        (
            [_id] => $group_name
            [total_sum] => Array
                (
                    [$sum] => 1
                )

        )

)

I'm getting this: [errmsg] => exception: A pipeline stage specification object must contain exactly one field. However, when I'm using only $project or $group operator it works just fine.

Sergey Tsibel
  • 1,595
  • 1
  • 18
  • 31

2 Answers2

4

The issue is your grouping your $project and $group together.

Your array should look more like

{
  $project: {
    group_name: 1,
    group_id: 1
  },
},
{   
  $group:{
    _id:{
      group_name:'$group_name',
    },
    total_sum:{$sum:1}
  }
}    
Adriano P
  • 2,045
  • 1
  • 22
  • 32
RedPhoenix
  • 306
  • 2
  • 3
0

You'll need to reformat and also use commas as separators. It's a pipeline so it takes each item in at a time.

I haven't tried this but try:

array
(
array(
array(
    '$project' => array(
        "group_name" => 1,
        "group_id"   => 1,
    )
),

array(
    '$group' => array(
        "_id" => array("group_name" => '$group_name'),
        "total_sum" => array('$sum' => 1),
    ),
)
)
Ricky Hartmann
  • 891
  • 1
  • 7
  • 20
  • I'm using commas in the code. This is just output for simplicity. Why did you put one extra array over another one? And no, didn't work – Sergey Tsibel Apr 02 '13 at 03:25