M201 Lab 2.1: Using Indexes to Sort

I can’t understand the DETAILED ANSWER to this:

db.people.find({ “first_name”: “Jessica”, “address.state”: { $lt: “S”} }).sort({ “address.state”: 1 })

Yes, while this query fails to use equality on the “address.state” field of the index prefix, it uses the same field for sorting.

With Compass the index is used in the query for ‘address.state’ too. No collection scan there.
What does mean “fails to use equality on the “address.state” field of the index prefix” ?

Hey @Cencio_Peravolos,

db.people.find({ “first_name”: “Jessica”, “address.state”: { $lt: “S”} }).sort({ “address.state”: 1 })

The above query will be used by the index and that is why you are not able to see any collection scan there.

The index given to us is:

{ "first_name": 1, "address.state": -1, "address.city": -1, "ssn": 1 }

The explanation line:

  • while this query fails to use equality on the “address.state” field of the index prefix, it uses the same field for sorting.*

means that the field though is not being used for equality but is being used for sorting, and since is a part of the prefix, hence is being used by the query. The course explains ESR Rule in the next chapter and this would become much more clearer then :smile:

Please let us know if there are any further doubts regarding this.

Regards,
Satyam

2 Likes

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.