Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB: Sort by array index

I have a document with an array field that contains a list of values and I would like to sort by the first element in the array.

{
   field1 : "bla",
   field2 : "bla",
   field3 : "bla",
   someArray : [123, 456, 789]
}

I was trying to query like this:

db.testCollection.find({}).sort({"someArray[0]" : 1})

But this does not seem to have any effect and the sort gets ignored.

Is there any way this can be done?

like image 253
ced-b Avatar asked Mar 28 '15 00:03

ced-b


People also ask

Does MongoDB sort use index?

Since indexes contain ordered records, MongoDB can obtain the results of a sort from an index that includes the sort fields. MongoDB may use multiple indexes to support a sort operation if the sort uses the same indexes as the query predicate.

How do I sort an array in MongoDB aggregation?

To sort the whole array by value, or to sort by array elements that are not documents, identify the input array and specify 1 for an ascending sort or -1 for descending sort in the sortBy parameter.

How do I sort elements in MongoDB?

To sort documents in MongoDB, you need to use sort() method. The method accepts a document containing a list of fields along with their sorting order. To specify sorting order 1 and -1 are used. 1 is used for ascending order while -1 is used for descending order.


1 Answers

Yes, the way to sort your collection by the first element of someArray in increasing order is:

db.testCollection.find().sort({"someArray.0": 1})

There is no need for the aggregation framework here. You were very close!

like image 103
AerandiR Avatar answered Oct 12 '22 23:10

AerandiR