Prefix for filter and sorting

I finished the Chapter 2 but ended up a little confused about the index when not using equality on the prefix.

As I understood, when the filtering is not using equality, the field is not used and doesn’t count for the “prefix”; so if I had this query:

db.people.find({ "first_name": "Jessica", "address.state": { $lt: "S"} }).sort({ "address.city": 1 }).explain("executionStats")

Having the same index from the lab 2.1:

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

Would it use the index for filter and sort? Since the “address.state” field wouldn’t be used because it’s not compared with equality.

I’m having trouble finding out if the sort is using an index. Hope someone can help me.

Thanks in advance!

Welcome to the confusion.

The thread Lab 2.1: Using Indexes to Sort helps.

1 Like

@ Mauricio_00306

Yes, it can be confusing; and I think it’s unfortunate that the full explanation of using indexes is spread over two chapters (Chapter 2: MongoDB Indexes, and Chapter 3: Index Operations) which also happen to be in two different weeks’ work. A lot of this will be much clearer (I think) once you have finished Chapter 3.

The way to determine what index is used in a query, and how it is used, is the explain() option. This is fully covered in Chapter 3, but if you want to peek ahead, look at the documentation here https://docs.mongodb.com/manual/reference/explain-results/ which gives a good description of how to use and interpret explain().

1 Like