Getting all data with highest value in MongoDB
Solution 1:
db.collection.aggregate([
{
$sort: {
version: -1
}
},
{
$group: {
_id: "$scanner",
version: {
$first: "$version"
},
test: {
$push: {
v: "$version",
id: "$_id",
p: "$project"
}
}
}
},
{
$project: {
items: {
$filter: {
input: "$test",
as: "item",
cond: {
$eq: [
"$$item.v",
"$version"
]
}
}
}
}
},
{
$unwind: "$items"
},
{
$project: {
scanner: "$_id",
_id: "$items.id",
project: "$items.p",
version: "$items.v"
}
}
])
Explained:
- Order(Sort) descending by version
- group by scanner taking the first value from the list per version and pushing all values in test array so we have suitable for filter in next stage
- Filter from test array only the elements with the max version we need
- Unwind the test array where only max values are filtered
- In the final $project stage rename the fields as per original names you need
playground