How to sort Documents in collection on basis of array fields

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 sort: 1.


```{
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" }
  ]
}

also, the hobbies could be null and hobbies values could be numbers and special characters.

Hello,

$unwind

Deconstructs an array field from the input documents to output a document for each element. Each output document is the input document with the value of the array field replaced by the element.

db.test.aggregate([{$unwind:"$hobbies"},{$sort:{"hobbies.value":1}}])

Thanks
WeDoTheBest4You

@wedothebest_We_do_the_Best
but after this query, I will group them(because I want a single doc for the same IDs). won’t they be disordered?

I put your query into mongoplayground so anyone can take a look to test:

It does seem that the actual output matches your requirements with just that sort. Note I added an ID just to make it clear the initial order and the output order.

Note that the ordering of item _id:3 is NOT changed, cycling is still last, however the overall ordering is changed.

I’m not sure how the query engine deals with sorting by an array as opposed to an actual value and from what I can see the documentation does not go into it further:

It does say how it deals with different types of values though, but that is not applicable to this case.

1 Like