2013-11-22 117 views
0

我是mongoDb的新手,在使用聚合函數時遇到問題。我試圖得到字段「期望」和「總體」的總和,但它返回0.我也想在同一個查詢中使用非空或空的註釋的總數。MongoDb php的聚合函數問題

$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" 

}

回答

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數據仍處於子文檔字段只是該子文檔已成爲單個審閱的對象。

該文檔對這個操作符有點誤導,我會給你。

+0

感謝它完美的工作!另外,如果我想要在同一個查詢中使用非空或空的評論總數,該怎麼辦? –

+0

@MarkGreen你可以做兩件事,你的樣品不會顯示評論欄,所以我有點猜測,但是如果你做兩次展開,它會有效地解開你的兩個朋友,然後你應該能夠總結出兩個部分。 – Sammaye

+0

@MarkGreen增加了一些樣本 – Sammaye