Home > Mobile >  how to get the maximum from a list of records with multiple similar documents in Monogodb?
how to get the maximum from a list of records with multiple similar documents in Monogodb?

Time:09-21

im new to Mongodb, i have collection which looks like this;

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"

I want to pass a specific empno for example 6000 to the query and I need to get the max points he has in the table. Where the output should be

80

how can I do this?

CodePudding user response:

Query

  • filter the empno
  • group by null (all table 1 group, because all documents are from 1 employ after the filter)
  • take the max
  • project to keep only 1 field

Test code here

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