arisalexis
arisalexis

Reputation: 2210

Aggregate match query with date extraction in MongoDB

I would like to find all documents that equal the team and year. The created_at field holds a date. The date aggregation operator $month works find in the second part of the query but the eq syntax is confusing.

db.getCollection('datas').aggregate([
    { $match : { team_id: '5824a4623bfd05018197792d', $eq: [{ $year: "$created_at" },"2016"] } },
    { $group: { _id: { $month: "$created_at" }, avg: { $avg: "$salary" }, count: { $sum: 1 } } }
]);

"errmsg" : "bad query: BadValue: unknown top level operator: $eq",

sample document:

{
    "_id" : ObjectId("5824dc9134ddc60d2e5d0a66"),
    "team_id" : "5824dc9134ddc60d2e5d0a64",
    "salary" : 60,
    "created_at" : ISODate("2016-11-10T20:46:07.045Z"),
    "__v" : 0
}

Upvotes: 1

Views: 2077

Answers (1)

Tomzan
Tomzan

Reputation: 2818

You can do it by projecting the year first:

db.getCollection("datas").aggregate([
    { $match: { team_id: "5824a4623bfd05018197792d" } },
    { $project: { salary: "$salary", created_at: "$created_at", year: { $year: "$created_at" } } },
    { $match: { year: 2016 } },
    { $group: { _id: { $month: "$created_at" }, avg: { $avg: "$salary" }, count: { $sum: 1 } } }

Upvotes: 3

Related Questions