英文:
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: "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?
答案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: "German Sheperd"})
You can also provide an argument to the explain
function, to determine its verbosity, like this:
db.Dog.explain('executionStats').findOne({name: "German Sheperd"})
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论