Shamoon
Shamoon

Reputation: 43639

Why can't I aggregate with MongoDB with a $match?

My code is:

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

It returns an error: "exception: A pipeline stage specification object must contain exactly one field."

However, if I do it without the $match, then it returns as expected. What am I doing wrong?

Upvotes: 1

Views: 49

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 312149

Put each pipeline stage into its own object within an array:

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

Upvotes: 3

Related Questions