Java – mongodb selects all fields, groups them by one field, and sorts them by another
We have a collection of 'messages' for the following fields
_id | messageId | chainId | createOn 1 | 1 | A | 155 2 | 2 | A | 185 3 | 3 | A | 225 4 | 4 | B | 226 5 | 5 | C | 228 6 | 6 | B | 300
We want to select all document fields according to the following criteria
>Interference through the field 'chainid' > sort by 'createdon' in desc order (sort)
So the expected result is
_id | messageId | chainId | createOn 3 | 3 | A | 225 5 | 5 | C | 228 6 | 6 | B | 300
We use spring - data in Java applications I've tried a different approach and it hasn't helped so far Is it possible to achieve the above objectives through a single query?
Solution
What you want is functionality that can be implemented through the aggregation framework The basic form of (useful to others) is:
db.collection.aggregate([ // Group by the grouping key,but keep the valid values { "$group": { "_id": "$chainId","docId": { "$first": "$_id" },"messageId": { "$first": "$messageId" },"createOn": { "$first": "$createdOn" } }},// Then sort { "$sort": { "createOn": -1 } } ])
This allows you to "group" different values of "messageid" and get $first boundary values for each other field Or, if you want the largest, use $last instead, but for the smallest or largest row, it may first make sense for $sort, otherwise just use @ L_ 403_ 3 @ and $max, if the whole line is not important
For more information about using, please refer to the mongodb aggregate () documentation, as well as the driver JavaDocs and springdata Mongo connector documentation for more usage of aggregation methods and possible helpers