同一查询中的多个聚合

时间:2014-10-02 10:06:30

标签: mongodb mongodb-query aggregation-framework

我有一个问题,我不知道如何使用MongoDB语法解决它。 实际上,这是我的实际查询:

db.traitement".aggregate {$match: {timestampentre: {$gt: start}, timestampentre: {$lt: end}}}, {$project: {year: {$year: "$date_entre"}, month: {$month: "$date_entre"}, "carnetsanitairedone.isDoneDouche": "$carnetsanitairedone.isDoneDouche", "carnetsanitairedone.isDoneDetartrage": "$carnetsanitairedone.isDoneDetartrage"}}, {$group: {_id: {year: "$year", month: "$month", "carnetsanitairedone.isDoneDouche": "$carnetsanitairedone.isDoneDouche", "carnetsanitairedone.isDoneDetartrage": "$carnetsanitairedone.isDoneDetartrage"}, count: {$sum: 1}}}

返回结果集:

[ { _id:
     { year: 2014,
       month: 10,
       'carnetsanitairedone.isDoneDouche': false,
       'carnetsanitairedone.isDoneDetartrage': false },
    count: 1 },
  { _id:
     { year: 2014,
       month: 10,
       'carnetsanitairedone.isDoneDouche': true,
       'carnetsanitairedone.isDoneDetartrage': true },
    count: 1 },
  { _id:
     { year: 1970,
       month: 1,
       'carnetsanitairedone.isDoneDouche': false,
       'carnetsanitairedone.isDoneDetartrage': false },
    count: 1 },
  { _id:
     { year: 1970,
       month: 1,
       'carnetsanitairedone.isDoneDouche': true,
       'carnetsanitairedone.isDoneDetartrage': true },
    count: 2 } ]

我真正需要的是以下结果集:

    'year': 2014,
    'month': 10,
    'count.isDoneDouche': 10,
    'count.isNotDoneDouche': 20,
    'count.isDoneDetartrage': 30,
    'count.isNotDoneDetartrage': 13

你能帮我解决这个问题吗?

感谢您提前

1 个答案:

答案 0 :(得分:1)

对于您提供的_id值,您可以使用$sum运算符有条件地$cond项:

db.traitement.aggregate([ 
   { "$match": {
       "timestampentre": { "$gt": start, "$lt": end}
   }}, 
   { "$group": {
       "_id": {
           "year": { "$year": "$date_entre" },
           "month": { "$month": "$date_entre" }
       },
      "countIsDoneDouche": {
          "$sum": {
              "$cond": [
                  "$carnetsanitairedone.isDoneDouche",
                  1,
                  0
              ]
          }
      },
      "countIsNotDoneDouche": {
          "$sum": {
              "$cond": [
                  { "$ne": [ "$carnetsanitairedone.isDoneDouche", true ] },
                  1,
                  0
              ]
          }
      },
      "countIsDoneDetartrage": {
          "$sum": {
              "$cond": [
                  "$carnetsanitairedone.isDoneDetartrage",
                  1,
                  0
              ]
          }
      },
      "countIsNotDoneDetartrage": {
          "$sum": {
              "$cond": [
                  { "$ne": [ "$carnetsanitairedone.isDoneDetartrage", true ] }
                  1,
                  0
              ]
          }
      }
  }}
])

这允许每个$cond操作中提供的“三元”的条件来确定“计数器”是否增加当前值。