2014-01-09 44 views
2

我想對文檔集合執行一些聚合。該文件是這樣的:MongoDB - 如何在聚合管道中使用多個組?

{name: "Sara", brandId: 1, count: 2 day:1/6/2014}//day value is ISODate 
{name: "Sally", brandId: 1, count: 5 day:1/7/2014} 
{name: "Mike", brandId: 1, count: 2, day: 1/8/2014} 
{name: "Bob", brandId: 1, count: 4 day: 1/8/2014} 
{name: "Joe", brandId: 1, count: 5 day:1/8/2014} 

我所試圖做的是讓所有的「計數」值的總金額。然後,我想按日期範圍對文檔進行分組,並獲得第二個分組的總和。因此,我願做這樣的事情:

db.people.aggregate(
    { $match : { BrandId : 4 } }, 
    { $group : { 
     _id : "$brandId", 
     TotalCount : { $sum : "$count" } //get the sum of all document 'count'  
    }}, 
    {$match: { 
    'Day': { $gte: new Date(2014, 0, 6), 
     $lte: new Date(2014, 0, 8)} 
    }}, 
    { $group : { 
     _id : "$BrandId", 
     countInTimeRange : { $sum : "$count" } //get the sum of 'count' within time range 
    }} 
    ) 

所以我想獲得的計數爲所有匹配的文件,然後按日期範圍過濾他們,並得到過濾的日期範圍匹配的文檔的總金額。 這可能嗎?

謝謝!

回答

3

我能在$ group操作中使用$ cond找到解決方案。

db.project.aggregate(
{ $match : { brandId : 4 } }, 
{ $project : { 
    _id : 0, 
    brandId : 1, 
    count : 1, 
    day : 1} 
}, 
{ $group : { 
    _id : "$brand", 
    TotalCount : { $sum : "$count" },   
    countInTimeRange : {$sum: { $cond: [ { $and: [{$gte: [ "$day", new Date(2014, 0, 6) ] }, {$lte: [ "$day", new Date(2014, 0, 8) ] }] }, "$count", 0 ] }} 

}}  
)