Mongo聚合查询用于计算多个计算值

时间:2017-05-04 15:35:11

标签: mongodb aggregation-framework

鉴于以下文件。

{
    _id: 1,
    ExpirationDate: ISODate("2017-05-02T09:29:46.006+0000")
}
{
    _id: 2,
    ExpirationDate: ISODate("2017-05-12T09:29:46.006+0000")
}
{
    _id: 3,
    ExpirationDate: ISODate("2017-05-23T09:29:46.006+0000")
}

如何使用聚合pipleline计算以下输出?

{
    "NumberOfSubscriptionExpiringToday": 12,
    "NumberOfSubscriptionExpiringWithInAWeek": 4
}

我希望用一个查询而不是两个查询来完成此任务。这是我到目前为止所拥有的......

.aggregate([
    { 
        $match: {
            "ExpirationDate": {
                $gte: ISODate("2017-05-02T00:00:00.000+0000"), 
                $lte: ISODate("2017-05-03T00:00:00.000+0000")
            }
        }
    },
    {  
        $project: {
            _id: 1
        }
    },
    { 
        $count: "ExpiringToday"
    }
]);


.aggregate([
    { 
        $match: {
            "ExpirationDate": {
                $gte: ISODate("2017-05-02T00:00:00.000+0000"), 
                $lte: ISODate("2017-05-08T00:00:00.000+0000")
            }
        }
    },
    {  
        $project: {
            _id: 1
        }
    },
    { 
        $count: "ExpiringInSevenDays"
    }
]);

1 个答案:

答案 0 :(得分:2)

您可以使用$cond运算符在单个聚合查询中执行此操作,以检查每个文档的到期日期是否属于[today, tomorrow)范围,还是[tomorrow, weekAfterToday)范围:

var today = ISODate("2017-05-04T00:00:00.000");
var tomorrow = ISODate("2017-05-05T00:00:00.000");
var weekAfterToday = ISODate("2017-05-11T00:00:00.000");

db.collection.aggregate([
  { $match: { "ExpirationDate": { $gte: today, $lt: weekAfterToday }}},
  {
      $project: {
        ExpiringToday: {
           $cond: {
               if: {
                   $and: [
                      {$gte: ["$ExpirationDate",today]},
                      {$lt:["$ExpirationDate",tomorrow]}
                   ]
               }, then: 1, else: 0
           }
        },
        ExpiringInAWeek: {
            $cond: { if: {$gte: ["$ExpirationDate",tomorrow]}, then: 1, else: 0 }
        }
      }
  },
  { $group: {
       _id: 1,
       NumberOfSubscriptionExpiringToday: {$sum: "$ExpiringToday" },
       NumberOfSubscriptionExpiringWithInAWeek: {$sum: "$ExpiringInAWeek" }
    }
  },
  { $project: { _id: 0 }}
 ]);

还要考虑提出两个简单的请求:

var numberOfSubscriptionExpiringToday = db.collection.count(
   { "ExpirationDate": { $gte: today, $lt: tomorrow }}
);

var numberOfSubscriptionExpiringWithInAWeek = db.collection.count(
   { "ExpirationDate": { $gte: tomorrow , $lt: weekAfterToday }}
);