How to sort by the first element of the array in mongodb?

Viewed 23

How can I sort the items by the first element in the array? Here is the example, the authors is an array list, and I want that the list is sorted by the first element.

"authors":"[John Doe, Mark Miller]"

I tried like below, but doesn't work.

db.collection('books')
    .find()
    .sort({ "authors[0]": 1 })
1 Answers

What you tried is working with small modification as follow:

db.collection('books')
.find()
.sort({ "authors.0": 1 })

And if collection is big it is best to improve performance with index as follow:

db.books.createIndex({"authors.0":1})
Related