Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongodb sorting children of an array in a document [duplicate]

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...

like image 469
McDermott Avatar asked Jun 28 '17 08:06

McDermott


People also ask

How do I sort an array in MongoDB aggregate?

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.

How can I sort into that nulls are last ordered in MongoDB?

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.

Does MongoDB support sorting?

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.


1 Answers

An option is to run an aggregation that:

  1. unwinds the array
  2. sorts by friends.name
  3. regroups

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'}}])
like image 193
kewne Avatar answered Oct 21 '22 00:10

kewne