My data looks like this:
{
"name":"dan",
"somestring":"asdf",
"friends":[
{
"name": "carl",
"height":180,
...
},
{
"name": "john",
"height":165,
...
},
{
"name": "jim",
"height":170,
...
}
]
},
...
I would like retrieve the document where the friends are sorted by height descending.
I tried db.getCollection('users').find({"name" : "dan"}, {"friends" : 1}).sort({"friends.height" : -1})
but the friends list stays the same.
EDIT: I messed up the structure of my data, I fixed the array to look like an array...
To sort the whole array by value, or to sort by array elements that are not documents, identify the input array and specify 1 for an ascending sort or -1 for descending sort in the sortBy parameter.
By adding the boolean property hasPrice, we can specify the order. We sorted the fields that have a value first, which ensures the ones without a price (zero or null values) are sorted last.
MongoDB can perform sort operations on a single-field index in ascending or descending order. In compound indexes, the sort order determines whether the index can be sorted.
An option is to run an aggregation that:
friends.name
The pipeline should look something like this:
db.collection.aggregate([
{ $match: { name: 'dan' }},
{ $unwind: '$friends' },
{ $sort: { 'friends.height': -1 }},
{ $group: { _id: '$name', friends: { $push: '$friends'}}])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With