ced-b
ced-b

Reputation: 4065

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?

Upvotes: 6

Views: 4616

Answers (3)

Pavan
Pavan

Reputation: 1

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

Upvotes: 0

AerandiR
AerandiR

Reputation: 5470

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!

Upvotes: 11

Neo-coder
Neo-coder

Reputation: 7840

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()

Upvotes: 0

Related Questions