Home > Back-end >  Behavior when sorting an array with multiple objects in it in MongoDB
Behavior when sorting an array with multiple objects in it in MongoDB

Time:11-11

I have this collection.

[
  {
    "id": 0,
    "name": [
      {
        "family": "A",
        "given": [ "Z" ],
        "use": 0
      },
    ],
  },
  {
    "id": 1,
    "name": [
      {
        "family": "Z",
        "given": [ "A" ],
        "use": 1
      },
    ],
  },
]

I naturally understand the behavior of the following sort on name.family.

db.collection.aggregate([
  {
    $sort: {
      "name.family": 1
    }
  }
])

However, I do not fully understand how mongo behaves when sorting on the entire name array as in playGround.

In this case, is it sorted in the first place?

If sorted, how and where does mongoDB refer to the array?

Thanks.

CodePudding user response:

TLDR; In this instance, Mongo Recursively compares key-value pairs in the order that they appear within the BSON object.

All info from docs: https://www.mongodb.com/docs/manual/reference/bson-type-comparison-order/

Mongo sorts in the following order:

1) MinKey (internal type)
2) Null
3) Numbers (ints, longs, doubles, decimals)
4) Symbol, String
5) Object
6) Array
7) BinData
8) ObjectId
9) Boolean
10) Date
11) Timestamp
12) Regular Expression
13) MaxKey (internal type)

So whilst name is an array, the item in that array is an object, so I believe that it: Recursively compare key-value pairs in the order that they appear within the BSON object. (From docs linked above)

In your playground example, {$sort:{"name":1}}, the first field of the first entry is 'family' therefore the first sort operation is executed on that field for that document.

If you change the first object so that it has a different first field:

{
  "use": 0,
  "family": "A",
  "given": [
    "Z"
  ]
}

The order sort will use the use key in ascending order give you a different result.

  • Related