“findOne” 和 “find” 在 MongoDB 中是否循环遍历集合?

huangapple go评论48阅读模式
英文:

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

问题

如果我有一个名为 "dog" 的集合。我想要找到具有品种 "German Shepherd" 的文档。某种方式,包含 "German Shepherd" 在其 "breed" 字段中的文档是最后插入的,这意味着文档位于集合的末尾。

如果我执行以下操作:

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

或者

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

假设我没有对任何字段建立索引,它是否会迭代每个文档直到找到包含 "German Shepherd" 的最后一个文档?

它是否与JavaScript中的以下for循环相同?

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

如果我有100万个类似的文档在一个集合中,基于字段的值或条件查找文档需要多长时间?

(Note: I've corrected the spelling of "Shepherd" in the text as "Sheperd" appeared to be a typo.)

英文:

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: &quot;German Sheperd&quot;})

or

db.Dog.findOne({name: &quot;German Sheperd&quot;}) 

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&lt;dogs.length; i++){
          const dog = dogs[i];
          if(dog.name == &quot;German Sheperd&quot;){
               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?

答案1

得分: 0

你可以检查查询EXPLAIN计划,以确定如何搜索匹配的文档,就像这样:

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

你还可以向explain函数提供参数,以确定其详细程度,就像这样:

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

通常情况下,如果你没有任何索引,你会看到一个名为COLLSCAN的阶段,它表示集合扫描,这意味着每个文档都会被查找,直到找到匹配的文档。

这里阅读更多关于explain函数的信息。

英文:

You can check the query EXPLAIN plan, to determine how the matching documents are searched for, like this:

db.Dog.explain().findOne({name: &quot;German Sheperd&quot;})

You can also provide an argument to the explain function, to determine its verbosity, like this:

db.Dog.explain(&#39;executionStats&#39;).findOne({name: &quot;German Sheperd&quot;})

Normally, if you don't have any indexes, you will see a stage named COLLSCAN, which refers to a collection scan, which means each and every document was looked up until a match is found.

Read more about the explain function here.

huangapple
  • 本文由 发表于 2023年1月9日 12:03:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/75053086.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定