Below is sample doc of collection.
{
name:"sam",
age:20,
hobbies: [ {id:1, value: "football"}, {id:2 value:"chess"} ]
},
{
"name": "Bob",
"age": 30,
"hobbies": [
{ "id": 1, "value": "painting" },
{ "id": 2, "value": "gardening" }
]
},
{
"name": "Charlie",
"age": 22,
"hobbies": [
{ "id": 1, "value": "cycling" },
{ "id": 2, "value": "playing the guitar" },
{ "id": 3, "value": "photography" }
]
}
I have tried using the below query, it only sorts the array of hobbies not the documents of the collection.
{$sort : {"hobbies.value": -1}}
I want to sort documents of the collection based on hobbies.value and also sort objects inside the array.
The expected result will be something like below for asc. .
{
name:"sam",
age:20,
hobbies: [ {id:2 value:"chess"}, {id:1, value: "football"} ]
},
{
"name": "Charlie",
"age": 22,
"hobbies": [
{ "id": 1, "value": "cycling" },
{ "id": 2, "value": "playing the guitar" },
{ "id": 3, "value": "photography" }
]
},
{
"name": "Bob",
"age": 30,
"hobbies": [
{ "id": 1, "value": "painting" },
{ "id": 2, "value": "gardening" }
]
}
2
Answers
Your current query is sorting the
hobbies.value
array by descending not ascending. You should use{ "hobbies.value": 1 }
To sort the objects in an array, you need the
$sortArray
operator.Demo @ Mongo Playground
Sorting documents by an array field is not intuitive. From the Comparison Sort Order docs:
{$sort:{"hobbies.value":-1}}
would sort the sample documents you provided in the order Charlie, Bob, Sam, because the values considered for the sort would be "playing the guitar", "painting", and "football".to sort the values within the array, use the $sortArray operator in a $project or $addFields stage.