I have mongo documents with the following structure:
{
name: 'AKL to DUD Via CHC',
rates: [
{
container_id: 'abc',
buyRate: 380
},
{
container_id: 'def',
buyRate: 410
}
]
}
{
name: 'AKL to DUD',
rates: [
{
container_id: 'abc',
buyRate: 400
},
{
container_id: 'def',
buyRate: 420
}
]
}
I would like to have a sort in my aggregation pipeline based on the buyRate of a specific container_id, e.g. if I passed in a container_id of abc I would like to sort on the buyRate of just abc so that (in this case) the second document is returned first.
I can get it working by adding in a field with rates filtered by the container_id and then sorting on that but it seems overly complex:
db.services.aggregate([
{ $addFields: { "containerBuyRate":
{ $filter: {
input: "$rates",
as: "rate",
cond: { $eq: [ "$$rate.container_id", "abc") ] }
}}
}},
{ $sort: {'containerBuyRate.buyRate': -1}}
])
Is there a more concise way to achieve this?