基于最大值的MongoDB聚合过滤器

时间:2020-02-13 12:33:15

标签: mongodb aggregation-framework

假设我有一个文档结构,其中一个字段X是一个数组av对象,如下所示。

"X" : [ 
    {
      "A" : "abc",
      "B" : 123
    },
    {
      "A" : "wer",
      "B" : 124
    },
    {
      "A" : "fgh",
      "B" : 124
    }
]

如何仅将B字段值最高的文档投影?如果最大值由多个文档共享,我只想返回其中一个(不重要的是哪个)。在这种情况下,结果可能类似于:

"X" : [ 
    {
      "A" : "wer",
      "B" : 124
    }
]

3 个答案:

答案 0 :(得分:2)

那一个呢?

db.collection.aggregate([
   {
      $set: {
         X: {
            $filter: {
               input: "$X",
               cond: { $eq: ["$$this.B", { $max: "$X.B" }] }
            }
         }
      }
   },
   { $set: { X: { $arrayElemAt: ["$X", 0] } } }
])

答案 1 :(得分:1)

您可以使用$reduce

  db.collection.aggregate([
      {
        "$project": {
          "X": {
            $reduce: {
              input: "$X",
              initialValue: {},
              in: {
                $cond: [ { "$gt": [ "$$this.B", "$$value.B" ]}, // Condition Check
                  "$$this",      // If condition true ($$this - Current Object)  
                  "$$value"      // If condition false $$value - Previous Returned Object
                ]
              }
            }
          }
        }
      }
    ])

Mongo Playground

答案 2 :(得分:0)

最新答案:

另一个导致最终返回完整对象的选项:


    [
    {$unwind: {
      path: "$X"
    }}, 
    {$sort: {
      "X.B": -1
    }}, 
    {$group: {
      _id: { _id: "$_id"},
      X: {
        $first: "$X"
      }
    }}]

原始答案:

您可以使用$ max运算符(https://docs.mongodb.com/manual/reference/operator/aggregation/max/)。

    [{$project: {
      X: {$max: "$X.B"}
    }}]