2015-04-05 46 views
0

我有以下問題子文檔和更新的聚集。我發現並總結了每個子文檔中的值。
它提供了以下[ { _id: 551fb140e4b04589d8997213, sumOfpeople: 342 } ]MongoDB的 - 其結果

我想借此sumOfpeople並將其插入到相同的房子(同樣req.params.house_id)

House.aggregate([ 
        { $match: { 
         id: req.params.house_id 
        }}, 
        { $unwind: '$people' }, // unwind creates a doc for every array element 
        { $group: { 
         _id: '$_id', 
         sumOfpeople: { $sum: '$people.nr'} 
        }} 
       ], function (err, result) { 
        if (err) { 
         console.log(err); 
         return; 
        } 


        console.log(result); 
       }); 

這是我想結果插入模型聚合成後。

module.exports = mongoose.model('House', { 

    id: String, 
    people: [{ 
    id: String, 
    nr: Number 
    }], 
    sumOfpeople: Number //this is the field that I want to update after the aggregation 

}); 

我曾嘗試使用$組:{sumOfpeople:{$總和: '$ people.nr'}}。 是否有可能使用$聚合內部設置,或者怎麼能解決,否則?

回答

0

有MongoDB中沒有辦法直接寫結果到現有的文檔,同時做一個彙總。

你有2種選擇:

  1. 檢索應用程序代碼的結果,然後在第二個查詢更新文檔。

  2. 使用$out運營商,將聚集的結果寫入到一個新的集合。該操作將刪除結果集合中的所有文檔並插入新文檔。 (http://docs.mongodb.org/manual/reference/operator/aggregation/out/