Sorting by document values in nested arrays in Mongo
I have a collection called "Objects". Each Object document has a nested array of documents called properties. Every property document has a name and a value.
For example, let's say I have these two objects, each with two properties (height and width). How to sort objects by height?
{
"id": 1,
"properties": [
{
"name": "height",
"value": 170
},
{
"name": "width",
"value": 200
},
]
},
{
"id": 2,
"properties": [
{
"name": "height",
"value": 100
},
{
"name": "width",
"value": 300
},
]
}
source to share
Most of the time MongoDB aggregation framework
is your friend when you are dealing with arrays. Have a look at $unwind
which can be used to split an array into separate documents. I've posted a sample request below to sort the documents height
. Note that you can use the operator $project
in the aggregation pipeline to better format the results.
db.objects.aggregate([
// De-normalize the 'properties' array
{$unwind:"$properties"},
// Filter for only height
{$match:{"properties.name":"height"}},
// Sort by 'height' in ascending order. Use -1 for descending
{$sort:{"properties.value":1}}
])
EDIT: One way to keep the item properties
intact is to make a copy of it just for sorting. Below is an example:
db.objects.aggregate([
// Make a copy of the 'properties' element
{$project:{properties:1, sortfield:"$properties"}},
{$unwind:"$sortfield"},
{$match:{"sortfield.name":"height"}},
{$sort:{"sortfield.value":1}},
// Get rid of 'sortfield'
{$project:{properties:1}}
])
source to share