$sortArray (Sort Elements Within Array)

Last updated: 2026-10-09

$sortArray (Sort Elements Within Array)

$sortArray sorts the elements inside an array and is new in MongoDB 5.2. Scalar arrays use a plain 1 (ascending) or -1 (descending); object arrays specify sort keys with { field: 1/-1 } or the array form [ [ 'field', 1 ] ] for multi-key sorting. Typical uses: ordering comments by time descending or products by price ascending before display. It returns a new array without mutating the source; an empty sortBy object throws an error.

CategoryArray
MongoDB Version1.0+
Example Languagemongosh (Shell)

📝 Syntax

{ $sortArray: { input: <array>, sortBy: <sortSpec> } }

⚙️ Parameters

inputThe array to sort.
sortByThe sort specification: 1/-1 for scalar arrays; { field: 1/-1 } or [ [ 'field', 1 ] ] for object arrays.

Returns:A new array with sorted elements

▶ Example

Run the commands below in your local mongosh (requires a running mongod):

// $sortArray: sort items by price ascending
db.orders.aggregate([
  { $project: {
      sorted: { $sortArray: { input: '$items', sortBy: { price: 1 } } }
  } }
])

Output:

{ '_id': 1, 'sorted': [ { 'sku': 'B', 'price': 5 }, { 'sku': 'A', 'price': 9 } ] }

📌 Notes

More hands-on cases coming soon.

📚 Related Tutorials

❓ FAQ

QDoes $sortArray support multi-field sorting?
AYes — use the form [ [ 'field1', 1 ], [ 'field2', -1 ] ].
QDoes it work on older MongoDB?
ANew in 5.2; on older versions $unwind, sort with $sort, then re-group.
QWhere do elements missing the key sort?
AThey sort to the end of the array.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏