问题
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.
回答1:
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}
}
}
回答2:
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),
),
)
)
来源:https://stackoverflow.com/questions/15753317/mongodb-group-and-project-operators