Mongodb 简明教程
MongoDB - Covered Queries
在本章中,我们将了解覆盖查询。
In this chapter, we will learn about covered queries.
What is a Covered Query?
根据官方 MongoDB 文档,覆盖查询是一个查询,其中 −
As per the official MongoDB documentation, a covered query is a query in which −
-
All the fields in the query are part of an index.
-
All the fields returned in the query are in the same index.
由于查询中显示的所有字段都是索引的一部分,因此 MongoDB 匹配查询条件并使用同一索引返回结果,而无需实际查看文档内部。由于索引存在于 RAM 中,所以与通过扫描文档获取数据相比,从索引中获取数据快得多。
Since all the fields present in the query are part of an index, MongoDB matches the query conditions and returns the result using the same index without actually looking inside the documents. Since indexes are present in RAM, fetching data from indexes is much faster as compared to fetching data by scanning documents.
Using Covered Queries
要测试覆盖查询,请考虑 users 集合中的以下文档 −
To test covered queries, consider the following document in the users collection −
{
"_id": ObjectId("53402597d852426020000003"),
"contact": "987654321",
"dob": "01-01-1991",
"gender": "M",
"name": "Tom Benzamin",
"user_name": "tombenzamin"
}
我们首先使用以下查询在 users 集合的 gender 和 user_name 字段上创建复合索引 −
We will first create a compound index for the users collection on the fields gender and user_name using the following query −
>db.users.createIndex({gender:1,user_name:1})
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}
现在,此索引将涵盖以下查询 −
Now, this index will cover the following query −
>db.users.find({gender:"M"},{user_name:1,_id:0})
{ "user_name" : "tombenzamin" }
也就是说,对于上面的查询,MongoDB 不会进入数据库文档中查找。相反,它将从索引数据中获取必需的数据,这是非常快速的。
That is to say that for the above query, MongoDB would not go looking into database documents. Instead it would fetch the required data from indexed data which is very fast.
由于我们的索引不包含 _id 字段,因此我们已将其明确地从查询结果集中排除,因为 MongoDB 默认在每个查询中返回 _id 字段。因此,以下查询不会覆盖在上面创建的索引中 −
Since our index does not include _id field, we have explicitly excluded it from result set of our query, as MongoDB by default returns _id field in every query. So the following query would not have been covered inside the index created above −
>db.users.find({gender:"M"},{user_name:1})
{ "_id" : ObjectId("53402597d852426020000003"), "user_name" : "tombenzamin" }
最后,请记住,如果 −
Lastly, remember that an index cannot cover a query if −
-
Any of the indexed fields is an array
-
Any of the indexed fields is a subdocument