Younas
Younas

Reputation: 131

MongoDB aggregate error: expression must have exactly one field

I have the following collection:

{
  "_id" : ObjectId("5c3f744a0f05e90001e0085a"),
  "date" : ISODate("2016-01-12T12:00:00.779Z"),
}

I need to group my documents by WEEK so I came up with this solution:

db.collection.aggregate([
  {
    $group : {
      _id: { $year: { date: '$date' }, $week: { date: '$date' } },
      date: { $first: '$date' }
    }
  },
  {
    $sort: { date: -1 }
  }
]);

But when I run this I get this error:

An object representing an expression must have exactly one field: { $year: { date: "$date" }, $week: { date: "$date" } }

How can this be fixed or is there any better solution? Thanks

Upvotes: 5

Views: 10391

Answers (1)

Younas
Younas

Reputation: 131

Problem solved naming the expressions:

db.collection.aggregate([
  {
    $group : {
      _id: {
        year: { $year: { date: '$date' } },
        week: { $week: { date: '$date' } }
      },
      date: { $first: '$date' }
    }
  },
  {
    $sort: { date: -1 }
  }
]);

Upvotes: 5

Related Questions