【问题标题】:how to get the maximum from a list of records with multiple similar documents in Monogodb?如何从 Monogodb 中具有多个相似文档的记录列表中获取最大值?
【发布时间】:2021-09-20 20:57:22
【问题描述】:

我是 Mongodb 的新手,我的收藏看起来像这样;

empno   points    date_saved

6000    80        "2021-09-18T08:25:49.319Z"
5000    60        "2021-09-18T08:25:49.319Z"
7000    70        "2021-09-18T08:25:49.319Z"
6000    60        "2021-09-17T08:25:49.319Z"

我想将特定的 empno 例如 6000 传递给查询,并且我需要获取他在表中的最大点数。输出应该在哪里

80

我该怎么做?

【问题讨论】:

    标签: mongodb mongoose mongodb-query


    【解决方案1】:

    查询

    • 过滤员工号
    • 按 null 分组(所有表 1 组,因为所有文档都来自过滤后的 1 个雇员)
    • 取最大值
    • 项目只保留 1 个字段

    Test code here

    db.collection.aggregate([
      {
        "$match": {
          "empno": {
            "$eq": 6000
          }
        }
      },
      {
        "$group": {
          "_id": null,
          "max-points": {
            "$max": "$points"
          }
        }
      },
      {
        "$project": {
          "_id": 0,
          "max-points": 1
        }
      }
    ])
    

    【讨论】:

    • 非常感谢,效果很好。有没有办法只获得最大点值?
    • 是的,我删除了更新中的任何额外字段,现在返回 {"max-points": 80},MongoDB 文档中的示例非常好。
    • 非常感谢
    猜你喜欢
    • 1970-01-01
    • 2019-06-30
    • 1970-01-01
    • 1970-01-01
    • 2020-12-02
    • 1970-01-01
    • 1970-01-01
    • 2020-11-03
    • 2017-09-20
    相关资源
    最近更新 更多