Mongodb group and project operators

落花浮王杯 提交于 2019-12-11 07:26:37

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!