简体   繁体   English

索引上方的慢MongoDB查询

[英]Slow MongoDB query on top of index

I have a collection in MongoDB with 1,7 million documents, with 6kb of size in average each document. 我在MongoDB中有一个集合,其中包含170万个文档,每个文档平均大小为6kb。 The database is in a reasonable machine, with 6Gb of RAM and 4 cores 该数据库位于一台合理的机器中,具有6Gb RAM和4个内核

This collection has an index to support my queries. 这个集合有一个索引来支持我的查询。 This index has the attributes bellow (String, String and Date) and is only 15 mb in size. 该索引具有以下属性(字符串,字符串和日期),大小仅为15 mb。 (Verified in MongoDB Compass) (在MongoDB Compass中验证)

{
    "Unit" : 1.0,
    "VendorCode" : 1.0,
    "EmissionDate" : 1.0
}

However, when I run the following query on the collection, it takes a long time to return. 但是,当我对集合运行以下查询时,需要很长时间才能返回。

db.Collection.find({
        'Unit': '016406',
        'EmissionDate': {$gte: new ISODate('2018-08-01')}
    }, {
        'Unit': 1,
        'VendorCode': 1,
        'EmissionDate': 1
    })

In my experience with SQL databases, such a query on top of an index of this size would return instantly. 根据我在SQL数据库中的经验,在此大小的索引之上的此类查询将立即返回。 However, when I run it on MongoDB, through the shell in the machine or Robo3T, it takes more than 10 minutes to complete! 但是,当我在MongoDB上通过计算机或Robo3T的外壳运行它时,要花10分钟以上才能完成!

My feeling is that, when the query finds the documents, for some reason Mongo is retrieving it from storage. 我的感觉是,当查询找到文档时,由于某种原因,Mongo正在从存储中检索文档。 But that is just a guess. 但这只是一个猜测。

Am I forgetting to take into account some basic best practices with MongoDB? 我是否忘记考虑MongoDB的一些基本最佳实践? Which ideas could you give me to investigate this problem? 您可以给我什么想法来调查这个问题?

Your index does not cover your criteria. 您的索引不符合您的条件。

'Unit': '016406',
'EmissionDate': {$gte: new ISODate('2018-08-01')}

You want another index: 您需要另一个索引:

{
    "Unit" : 1.0,
    "EmissionDate" : 1.0
}

Your existing index only support the follwing criteria: 您现有的索引仅支持以下条件:

{Unit}
{Unit, VendorCode}
{Unit, VendorCode, EmissionDate}

Read more about the prefix in compound index here 在此处阅读有关复合索引中前缀的更多信息

Bear in mind that mongodb will use at most one index or an index intersection to cover your query + sort (if any). 请记住,mongodb将最多使用一个索引或索引交集来覆盖您的查询+排序(如果有)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM