【问题标题】:Aggregate match query with date extraction in MongoDB在 MongoDB 中使用日期提取进行聚合匹配查询
【发布时间】:2016-11-10 17:04:23
【问题描述】:

我想查找与团队和年份相同的所有文档。 created_at 字段包含一个日期。日期聚合运算符 $month 可以在查询的第二部分找到,但 eq 语法令人困惑。

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",

示例文档:

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

【问题讨论】:

  • 不好意思,上面的查询又是什么问题???
  • 已更新,但我的语法完全错误
  • 能否请您也添加示例文档?
  • 刚刚做了,不过我看不出它有什么帮助

标签: mongodb


【解决方案1】:

您可以通过先预测年份来做到这一点:

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 } } }

【讨论】:

  • 这会产生 "errmsg" : "bad query: BadValue: unknown top level operator: $year"
猜你喜欢
  • 2019-01-24
  • 2015-12-05
  • 1970-01-01
  • 2015-09-06
  • 1970-01-01
  • 2020-12-22
  • 2017-02-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多