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?
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.
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.
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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With