MongoDb与PHP的聚合函数问题

时间:2013-11-22 07:44:45

标签: php mongodb

我是mongoDb的新手,在使用聚合函数时面临问题。我试图获得字段“期望”和“整体”的总和但它返回0.我还想在同一查询中获取非空或空的注释的总数。

$out = $collection->aggregate
(
    array(          
        array( '$match' => array( 'id' => 6200 )),
            array ('$unwind' => '$reviews'),
                array( '$group' => array( '_id' => '$id',
                    'exptotal' => array( '$sum' => array('reviews' => '$expectations') ),                   
                    'total' => array( '$sum' => array('reviews' => '$overall' ) ),                  
                    'count' => array( '$sum' => 1 )
                    )
            )
        )

);  

这是json

{
"_id": "528c62406a542f7c6a6bf522",
"id": 6200,
"categories": [
    {
        "id": 6,
        "name": "Artificial Intelligence"
    },
    {
        "id": 5,
        "name": "Statistics and Data Analysis"
    }
],
"courseId": "COURSE_16",
"institute": {
    "id": 5693,
    "name": "YZ University"
},
"instructors": [
    "  A Morris"
],
"language": "en",
"reviews": [
    {
        "username": "kalis",
        "expectations": 3,
        "content": 2,
        "overall": 3,
        "comments": "This is really good course for improvement",
        "datecreated": "2013-11-02T17:04:11.102Z"
    },
    {
        "username": "julia",
        "expectations": 4,
        "content": 2,
        "overall": 2,
        "comments": "This improves my skill a lot",
        "datecreated": "2013-11-03T17:04:11.102Z"
    },
    {
        "username": "john",
        "expectations": 2,
        "content": 4,
        "overall": 4,
        "comments": "",
        "datecreated": "2013-11-04T17:04:11.102Z"
    }
],
"shortName": "ml",
"title": "Machine Learning"

}

1 个答案:

答案 0 :(得分:0)

看起来它会起作用:

$out = $collection->aggregate(array(
    array('$match' => array( 'id' => 6200 )),
    array ('$unwind' => '$reviews'),
    array('$unwind' => '$comments'),
    array( '$group' => array( '_id' => '$id',
        'commTotal' => array('$sum' => array('$cond'=>array(array('$eq'=>array('$comments',null),0,1)))),
        'exptotal' => array( '$sum' => '$reviews.expectations'),
        'total' => array( '$sum' => '$reviews.overall' ),
        'count' => array( '$sum' => 1 )
    ))
));

原因是,当您$unwind数据仍在其子文档字段中时,只是子文档已成为单个审阅的对象。

文档对这个操作符有点误导我会给你。