1
votes

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 protected]"}

If this is the index:

db.getCollection('people').createIndex({ 
    "email": "[email protected]"  
    "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 protected]"})
    .sort({"lastName":1 }) 

Thank you for your help,

1

1 Answers

0
votes

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.