6

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?

0

3 Answers 3

11

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!

Sign up to request clarification or add additional context in comments.

1 Comment

Be interested in your thoughts on stackoverflow.com/questions/51711544/… if you have any spare time?
0

It is not ignoring the ascending sort, but it sorts according to min value in the each array.

1 Comment

This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From Review
-1

This thing not possible in directly mongo find query so you should use mongo aggregation as below

db.collectionName.aggregate({"$unwind":"$someArray"},{"$sort":{"someArray":-1}})

but above aggregation takes too much recurssion as it caused performance issue. So I think it should poosible to update someArray in sorting order and then used findquery so it shows results in someArray in sorted manner. Below query update someArray

db.collectionName.update({},{"$push":{"someArray":{"$each":[],"$sort":-1}}},false,true)

last true used for updating multiple documents. When update complete then simple find query as db.collectionName.find().pretty()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.