skip to content
Alvin Lucillo

Sort array in aggregation pipeline

/ 2 min read

You can use $sortArray expression operator to sort the values of an array. For example, see the location.coordinates value below. It’s sorted descendingly (e.g., [41, -74]) since it’s the order when the documents are created.

db.sightings.aggregate({$project: {_id: 1, specifies_common: 1, "location.coordinates": 1}})

[
  {
    _id: ObjectId('62cf2f0acfe5bbb25ee815fb'),
    location: { coordinates: [ 41, -74 ] }
  },
  {
    _id: ObjectId('62cf8ebfbb9cdbee29caab04'),
    location: { coordinates: [ 40, -74 ] }
  },
  {
    _id: ObjectId('62e2d811b1d5bc85b6e04013'),
    location: { coordinates: [ 41, -74 ] }
  },
  {
    _id: ObjectId('62cf8eb2bb9cdbee29caab03'),
    location: { coordinates: [ 40, -74 ] }
  },
  {
    _id: ObjectId('62cf8e9fbb9cdbee29caab02'),
    location: { coordinates: [ 40, -74 ] }
  },
  {
    _id: ObjectId('62cf32bdcfe5bbb25ee815fc'),
    location: { coordinates: [ 40, -73 ] }
  }
]

Nothing changed in the output. It’s still sorting arrays descendingly. We use $sortArray with pipeline stage $set, that changes the value of a property. In this case, it’s sorting the values. db.sightings.aggregate({$set: {"location.coordinates":{$sortArray: {input: "$location.coordinates", sortBy: -1}}}},{$project: {_id: 1, specifies_common: 1, "location.coordinates": 1}})

[
  {
    _id: ObjectId('62cf2f0acfe5bbb25ee815fb'),
    location: { coordinates: [ 41, -74 ] }
  },
  {
    _id: ObjectId('62cf8ebfbb9cdbee29caab04'),
    location: { coordinates: [ 40, -74 ] }
  },
  {
    _id: ObjectId('62e2d811b1d5bc85b6e04013'),
    location: { coordinates: [ 41, -74 ] }
  },
  {
    _id: ObjectId('62cf8eb2bb9cdbee29caab03'),
    location: { coordinates: [ 40, -74 ] }
  },
  {
    _id: ObjectId('62cf8e9fbb9cdbee29caab02'),
    location: { coordinates: [ 40, -74 ] }
  },
  {
    _id: ObjectId('62cf32bdcfe5bbb25ee815fc'),
    location: { coordinates: [ 40, -73 ] }
  }
]

Now, in the example below, we sorted the values in ascendingly (e.g., [-74, 41]). When you use sortBy: 1, it sorts the array in ascending order; if it’s sortBy -1, descending order.

db.sightings.aggregate({$set: {"location.coordinates":{$sortArray: {input: "$location.coordinates", sortBy: 1}}}},{$project: {_id: 1, specifies_common: 1, "location.coordinates": 1}})

[
  {
    _id: ObjectId('62cf2f0acfe5bbb25ee815fb'),
    location: { coordinates: [ -74, 41 ] }
  },
  {
    _id: ObjectId('62cf8ebfbb9cdbee29caab04'),
    location: { coordinates: [ -74, 40 ] }
  },
  {
    _id: ObjectId('62e2d811b1d5bc85b6e04013'),
    location: { coordinates: [ -74, 41 ] }
  },
  {
    _id: ObjectId('62cf8eb2bb9cdbee29caab03'),
    location: { coordinates: [ -74, 40 ] }
  },
  {
    _id: ObjectId('62cf8e9fbb9cdbee29caab02'),
    location: { coordinates: [ -74, 40 ] }
  },
  {
    _id: ObjectId('62cf32bdcfe5bbb25ee815fc'),
    location: { coordinates: [ -73, 40 ] }
  }
]