Just a learner
Just a learner

Reputation: 28592

Sorting a collection in MongoDB with multiple keys

I'm learning MongoDB and I found to sort a MongoDB collection you have to do something like:

db.people.find().sort({firstname: 1, lastname: 1})

This should correspond to ORDER BY firstname, lastname in SQL. In order to ORDER BY lastname, firstname, you have to use:

db.people.find().sort({lastname: 1, firstname: 1})

Note that {lastname: 1, firstname: 1} is a JSON object. So that seems the key order matters here. But from my understanding the keys of a JSON object should not take any significance. Where is wrong?

Upvotes: 0

Views: 2177

Answers (1)

SiddAjmera
SiddAjmera

Reputation: 39432

Use this to sort by multiple fields:

db.people.find().sort([
  ["firstname": 1],
  ["lastname": 1]
]);

Here, we can also use objects instead of arrays. But the order of sort may or may not be as specified. But in case of Arrays, it will be.

Upvotes: 2

Related Questions