Search code examples
mongodbmongodb-query

MongoDB Slow Query issue


I am facing slow query issue in my mongoDB database, the indexing is done properly, I have checked that there is no duplicate numeric id, even though I am getting a slow query issue. The query I am using is findOne in which it is scanning the entire data base and returning one document only. It is also reporting that in this operation it cannot able to use the index and the operation execution time is around 40-50 ms which is resulting is slow query issue. What could be done to avoid this scenario.

The collection looks like this

{_id: "MongoDBId";
userId: "MongoDBId";
arrFlield1: "arrayOfString";
arrField2 : "arrayOfString";
numericId : "Integer"}

And the query I am using is

db.collection.findOne({userId:"userId"})

Solution

  • After I attached the index to the particular querying field userId this issue was solved. The thing happened was that indexing was attached _id, it needs to be attached to querying field which was not done. As mentioned by @_prasad, I first get the Index using this command.

    db.collection.getIndexes()
    

    Then I created index on the particular query field by using the below command.

    db.collection.createIndex({userId:1})