简体   繁体   中英

List all documents from mongodb where the each document's one field has max value in spring boot

I have list of documents on mongodb like

Id, name, surname, salary. 

I want all documents would return which contains max salary . I know that i should aggregate the query in two step.

  1. First of all, I should find max value of salar field for all documents,
  2. and after then i should find all documents where salary equals maxValue.

But i cannot configure it neither JPA nor native query approach. How can i make it happen?

[{
 $group: {
  _id: '$salary',
  records: {
   $push: '$$ROOT'
  }
 }
}, {
 $sort: {
  _id: -1
 }
}, {
 $limit: 1
}]

Example of output

{
  "_id": 40,
  "records": [
    {
      "_id": {
        "$oid": "631b8ab07d8c3aa86bb1c5fc"
      },
      "name": "Bob",
      "surname": "B",
      "salary": 40
    },
    {
      "_id": {
        "$oid": "631b8ab07d8c3aa86bb1c5fd"
      },
      "name": "Alice",
      "surname": "A",
      "salary": 40
    }
  ]
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM