为什么我不能使用$ match与MongoDB聚合?

时间:2014-11-22 18:07:32

标签: mongodb aggregation-framework

我的代码是:

db.essays.aggregate({
  $match: {
    essayId: 3
  },
  $group: {
    _id: {
      year: {
        $year: '$essayTime'
      },
      month: {
        $month: '$essayTime'
      },
      day: {
        $dayOfMonth: '$essayTime'
      }
    },
    count: {
      $sum: 1
    }
  }
});

它返回错误:"exception: A pipeline stage specification object must contain exactly one field."

但是,如果我在没有$match的情况下执行此操作,则会按预期返回。我做错了什么?

1 个答案:

答案 0 :(得分:3)

将每个管道阶段放入数组中自己的对象中:

db.essays.aggregate([
  { $match: {
    essayId: 3
  }},
  { $group: {
    _id: {
      year: {
        $year: '$essayTime'
      },
      month: {
        $month: '$essayTime'
      },
      day: {
        $dayOfMonth: '$essayTime'
      }
    },
    count: {
      $sum: 1
    }
  }}
]);