【问题标题】:MongoDB - How can I use multiple groups in an aggregation pipeline?MongoDB - 如何在聚合管道中使用多个组?
【发布时间】:2014-01-28 11:08:20
【问题描述】:

我正在尝试对一组文档执行一些聚合。文件如下所示:

{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
    }}
    )

所以我想获取所有匹配文档的计数,然后按日期范围过滤它们并获取过滤的日期范围匹配文档的总和。 这可能吗?

谢谢!

【问题讨论】:

    标签: mongodb aggregation-framework nosql


    【解决方案1】:

    我能够在我的 $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 ] }}
    
    }}    
    )
    

    【讨论】:

      猜你喜欢
      • 2019-04-07
      • 2022-09-23
      • 1970-01-01
      • 1970-01-01
      • 2020-12-12
      • 2018-04-30
      • 2016-05-03
      • 2014-08-26
      • 1970-01-01
      相关资源
      最近更新 更多