Home > Back-end >  How to transform an array field into a value equaling its maximum?
How to transform an array field into a value equaling its maximum?

Time:01-20

{
   name: "use_name",
   grades: [
     {class: "math": grade: 100},
     {class: "english": grade: 90}
   ]
}

How do I write an aggregation pipeline to output:

{
   name: "use_name",
   grades: {class: "math": grade: 100},
   
}

The grades field has been reduced to the element where its grade property is the maximum of all elements.

The requirements, the aggregation pipeline cannot have $unwind or $group because it cannot have a stage where the stage needs to receive all incoming documents before outputting to the next stage, potentially exceeding the 100mb limit. And it must be fast.

CodePudding user response:

Replace $$value in $reduce until you find the max.

db.collection.aggregate([
  {
    $set: {
      grades: {
        "$reduce": {
          "input": "$grades",
          "initialValue": null,
          "in": {
            "$cond": {
              "if": {
                $or: [
                  {
                    $eq: [
                      null,
                      "$$value"
                    ]
                  },
                  {
                    $gt: [
                      "$$this.grade",
                      "$$value.grade"
                    ]
                  }
                ]
              },
              "then": "$$this",
              "else": "$$value"
            }
          }
        }
      }
    }
  }
])

Mongo Playground

  • Related