Does "findOne" and "find" in MongoDB loop through the collection?

Supposed I have a collection named dog. I want to find the document that has breed “German Shepherd”. Somehow the document that contains “German Shepherd” in its “breed” field is the last one inserted, which means the document is at the end of the collection.

If I do

db.Dog.findOne({name: "German Sheperd"})

or

db.Dog.findOne({name: "German Sheperd"})

Assume I have not indexed any field, does it iterate through each document until the document that contains “German Sheperd”, which is the last document, is foundd?

Is it same like the following for loop in JavaScript?

function findGermanShepard(dogs){
    for (let i=0; i<dogs.length; i++){
          const dog = dogs[i];
          if(dog.name == "German Sheperd"){
               return dog       
           } 
    }
   return null;
}

If I have 1 million documents in a collection like that, how long does it take to find a document based on a value of a field or a condition?

If you send a query of db.dog.find( {name: “German Shepard”}) the explain plan will show that without an index on name that there is a col scan, equivalent to the loop you have above. That is inefficient which why if you put an index on name you will cat an ixscan which is going to be much much faster.

4 Likes