Confused on the type of index to use

Hello there,

I’m trying to optimize my MongoDB collection for queries made from a service using the findOne method. Specifically, I need to query based on both the userId and userAccessCode fields, where each user can have up to 32 associated codes. The userId and userAccessCode properties are both saved as strings in the database. So each user can have upto 32 documents.

To improve query performance, I’ve created an index on these fields using the following code: db.collection.createIndex({ userId: 1, userAccessCode: 1 }). However, I haven’t noticed any performance improvements yet, and I’m wondering if there is a better type of index to use or if I’ve done everything correctly so far.

Here’s an example of what a document in my collection might look like:

{
  userId: "someid" // string,
  userAccessCode: "adcdsdfdf" // string,
  date: 'currentDate',
  // Other fields...
}

Thanks in advance :slight_smile:

If you can access the mongodb shell and run the findOne query you are running you can then add on the .explain(“executionStats”) and post it here that will be the best way to figure out what’s going on during the query.

db.collection.findOne({"userId":"someid", "userAccessCode": "adcdsdfdf"}).explain("executionStats")

If you could post the results of the explain that would be great :slight_smile:

1 Like

Compared to what? Is your query slow? How many userId you have? What are your collection sizes?