1

sort of a basic conceptual question regarding mongodb. Thank you in advance for your help.

If I have a compound index in mongodb using a non-primary key index, and I run a query, why is it still necessary to sort the return results when in theory, shouldn't the indexes themselves scan the documents in sorted order? Here is a quick example of what I'm trying to understand:

Document looks like this:

{"_id":123,
 "firstName":"John",
 "lastName":"Doe",
 "email":"email@email.com"}

If this is the index:

db.getCollection('people').createIndex({ 
    "email": "email@email.com"  
    "lastName": 1,
    "firstName": 1
})

If I wanted to return a list of documents by email, sorted by lastName, why is the .sort ({ ... }), still necessary to sort by last name? :

db.getCollection('people').find({"email":"email@email.com"})
    .sort({"lastName":1 }) 

Thank you for your help,

Johan B
  • 394
  • 1
  • 10

1 Answers1

0

That index doesn't "cover" the query, so MongoDB still needs to separately read the matched documents. And because you didn't specify a sort order, MongoDB is free to read and return the documents in whatever order it deems is easiest/most efficient, which is likely in the order the docs are stored on disk.

JohnnyHK
  • 305,182
  • 66
  • 621
  • 471