【问题标题】:Get the document with the max value of a field in MongoDB获取MongoDB中某个字段的最大值的文档
【发布时间】:2020-01-10 10:18:53
【问题描述】:

我正在使用聚合框架从一组文档的集合中获取字段的最大值,就像这样

db.getCollection('Collection').aggregate([
   {$match: {"product": {$in: ["product-a"]}}},
   {$group: {_id: null, maxPrice: {$max: "$price"}}}
])

但是如果我想获得符合这个条件的文档的 ID 怎么办?如何在管道的下一阶段做到这一点?

【问题讨论】:

    标签: mongodb mongodb-query aggregation-framework


    【解决方案1】:

    您可以像这样将所有字段放在$max 运算符中...它将为您提供最初在$max 对象中使用的最大字段的文档。只是我在这里用过price

    db.getCollection("Collection").aggregate([
      { "$match": { "product": { "$in": ["product-a"] } } },
      { "$group": {
        "_id": null,
        "maxPrice": {
          "$max": {
            "price": "$price",
            "_id": "$_id"
          }
        }
      }}
    ])
    

    【讨论】:

    • 非常感谢!我不知道为什么我没想到你可以在 $max 运算符中投影多个字段
    • 如果price 值相等,它会选择_id 最大的文档吗?
    • @GregoryPakosz 那么你应该把_id放在第一位。
    • 如果我把_id放在前面,那么它会选择_id最大的文档对吧?我想知道的是:比较中是否使用了_id。我会说是的,并且想确认两个文档的价格相同,然后_id 较大的文档获胜
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-25
    • 2016-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多