I have the following documents in the database. What I would like is to be able to sort the documents by the value of one of its subdocuments that's inside an array. Is this possible to do?
{
name: "Item A",
subItems: [{
name: "Subitem 1",
value: 10
},
{
name: "Subitem 2",
value: 20
}]
},
{
name: "Item B",
subItems: [{
name: "Subitem 1",
value: 5
},
{
name: "Subitem 2",
value: 60
}]
}
I would like to sort the documents by the value of one of the subitems so that the expected outcome for sorting by ascending would be below (in this case sorting by descending would also give the same result because item B has both lowest and largest value items). I don't really care for the order of the subitems in this query, just the order of the parent documents.
Expected outcome:
{
name: "Item B",
subItems: [{
name: "Subitem 1",
value: 5
},
{
name: "Subitem 2",
value: 60
}]
},
{
name: "Item A",
subItems: [{
name: "Subitem 1",
value: 10
},
{
name: "Subitem 2",
value: 20
}]
}
I know it will have to use aggregation but no idea how to even start with this. Any help appreciated.