0

A rather simple question but I don't have a database to test on...
If I sort on a value, will the order of my other values remain?

Say my mongoDB data looks like this

id, a
0, 1
1, 1
2, 2
3, 2

and I do sort on a, descending. Will the order of the ids remain? Like this?

id, a
2, 2
3, 2
0, 1
1, 1

On a related note, can i chain sorts after each other like this:

cursor.sort([("id",1)]).sort([("a",1)])

Will this ensure the results are sorted by a primarily and id secondarily?

Thank you for your help

  • YES, you can chain but sort require object not array. .sort({"_id": 1}).sort({ "a" : 1 }) [doc](https://docs.mongodb.com/manual/reference/method/cursor.sort/) – Ashok Oct 02 '19 at 08:53
  • 1
    A `.sort()` in MongoDB is applied to a `Cursor` result. This **does not permanently** alter the order of documents as they appear in a collection, nor does it **permanently** affect the retrieved order on subsequent queries. As the linked answer will note, creating an **index** on a specific field you want to **sort** on, would result in that order ( from the index ) being used on subsequent queries, as long as the query somehow "hinted" or otherwise indicated that index be used. In short, if an **index** is selected, then results maintain that order. But not otherwise without an explicit sort – Neil Lunn Oct 02 '19 at 10:08

1 Answers1

0

The documentation states

Result Ordering

Unless you specify the sort() method or use the $near operator, MongoDB does not guarantee the order of query results.

So you can infer that after the sorted fields, the order of any other fields cannot be guaranteed either.

From the same documentation you can also see that the sort function can take multiple fields, i.e.

db.orders.find().sort( { "item.category": 1, "item.type": 1 } )

It's only a few minutes to download mongodb and setup your own database to try stuff, give it a go!

Belly Buster
  • 8,224
  • 2
  • 7
  • 20