I’m adding indexes to my MongoDB database and want to ensure that I’m doing everything in the optimal fashion. I have a lot of queries where I will select a document based on the _id field, but then also need to validate that that document belongs to the current user by also querying by their user id.
For example:
'_id'=>"123", "user_id"=>10
I’m unsure of where I should put the index. Which is the best solution for the index..
- Just on _id
- A compound index of _id and user_id
- Something else
Should I really be passing the customer_id as a query field or should I return the customer id from MongoDB and check it using PHP code? Ie, would the query execute faster if it was just looking up _id rather than _id and customer_id. Would checking the customer id in PHP via an if statement be handled faster in PHP than via a query in MongoDB..
Any thoughts would be appreciated!
If you have an
_idin your query, the default_idindex will be good enough (you don’t need to create it). It’s a unique lookup. You don’t need to filter any more than that! The query shouldn’t run any slower if you have additional fields to filter on.