A document in my student
collection looks like this:
{
"sample": false,
"paid": true,
"status": 1,
"department": "1435334",
"ts" : ISODate("2022-04-20T04:51:00.731Z"),
}
There are some records, which do not have department
field. So another sample:
{
"sample": true,
"paid": true,
"status": 4,
"ts" : ISODate("2022-04-20T04:51:00.731Z"),
}
so I have a query which is like:
db.student.find({
"paid": true,
"sample": {"$ne": true},
"status": {"$ne": 4},
}).sort({'ts': -1}).limit(10)
If it is being paginated, then:
db.student.find({
"paid": true,
"sample": {"$ne": true},
"status": {"$ne": 4},
"ts": {"$lt": createdAt},
}).sort({'ts': -1}).limit(10)
sometimes I need to find students who belong to departments:
db.student.find({
"paid": true,
"sample": {"$ne": true},
"status": {"$ne": 4},
"ts": {"$lt": createdAt},
"department": {"$in": ["1", "2", "3"]}
}).sort({'ts': -1}).limit(10)
Now I want to know an optimal index which can cover these.
In my query, three things are always constant:
{ "paid": true, "sample": {"$ne": true}, "status": {"$ne": 4} }
so I want to add these to partial expression, so that my index has only these values.
Following ESR rule, I came with following index:
{
"key" : {
"status": 1,
"department": 1,
"ts": 1,
},
"name" : "idx_student_data",
"background" : true,
"partialFilterExpression" : {
"paid" : true,
}
}
- Is this index correct?
- Is this right way to use partial expressions?
- I am slightly confused about the ESR rule. Here
department
field in query is optional. do I need to create two indexes one with department and another without? It’s also in query, not equality.