Search code examples
mongodbsortingmaxmatchaggregate

MongoDB retrieve data with highest value


I have this collection in MongoDB:

[
  { _id: "...", "project": 244, "scanner": "powershell", "version": 2 },
  { _id: "...", "project": 244, "scanner": "powershell", "version": 3 },
  { _id: "...", "project": 244, "scanner": "powershell", "version": 4 },
  { _id: "...", "project": 244, "scanner": "powershell", "version": 4 }
]

I need to retrieve all the document with the highest version, in this case:

  { _id: "...", "project": 244, "scanner": "powershell", "version": 4 },
  { _id: "...", "project": 244, "scanner": "powershell", "version": 4 }

I can find the highest version, sorting with -1 and taking the first one.

How do I apply the result found to the filter?

Many thanks


Solution

  • playground

    db.collection.aggregate([
      {
        "$group": { //Find max value
          "_id": "null",
          "maxV": {
            "$max": "$version"
          },
          data: { // add all records to this array
            $push: "$$ROOT"
          }
        }
      },
      {
        $project: {
          "output": {
            $filter: {//Filter the matching record from the array in stage 1
              input: "$data",
              as: "d",
              cond: {
                $eq: [
                  "$$d.version",
                  "$maxV"
                ]
              }
            }
          },
          "_id": 0
        }
      }
    ])
    

    If you want to get rid of key output, you can two more stages as in this play

      {
        "$unwind": "$output"
      },
      {
        "$replaceRoot": {
          "newRoot": "$output"
        }
      }