【问题标题】:Mongo DB goes slow with increase in number of recordsMongodb随着记录数量的增加而变慢
【发布时间】:2018-01-31 05:56:04
【问题描述】:

我们使用了 mongo,它在测试服务器上运行良好(我认为是因为记录数量较少),但是当我们转向生产时,它变得很慢。即使是简单的查询也需要大约 10 秒的时间。

我也检查过索引,已经定义了适当的索引。

查询

       db.products.aggregate([{
       "$match": {
           "tenant_id": 1031
       }
   }, {
       "$sort": {
           "id": -1
       }
   }, {
       "$skip": 0
   }, {
       "$limit": 20
   }]
) 

解释结果

// collection: products
{
    "waitedMS" : NumberLong("0"),
    "stages" : [
        {
            "$cursor" : {
                "query" : {
                    "tenant_id" : 1031
                },
                "sort" : {
                    "id" : NumberInt("-1")
                },
                "limit" : NumberLong("20"),
                "queryPlanner" : {
                    "plannerVersion" : NumberInt("1"),
                    "namespace" : "dbname.products",
                    "indexFilterSet" : false,
                    "parsedQuery" : {
                        "tenant_id" : {
                            "$eq" : 1031
                        }
                    },
                    "winningPlan" : {
                        "stage" : "FETCH",
                        "filter" : {
                            "tenant_id" : {
                                "$eq" : 1031
                            }
                        },
                        "inputStage" : {
                            "stage" : "IXSCAN",
                            "keyPattern" : {
                                "id" : NumberInt("-1")
                            },
                            "indexName" : "id",
                            "isMultiKey" : false,
                            "isUnique" : false,
                            "isSparse" : false,
                            "isPartial" : false,
                            "indexVersion" : NumberInt("1"),
                            "direction" : "forward",
                            "indexBounds" : {
                                "id" : [
                                    "[MaxKey, MinKey]"
                                ]
                            }
                        }
                    },
                    "rejectedPlans" : [ ]
                }
            }
        }
    ],
    "ok" : 1
}

请告诉我我能做些什么让它更快

【问题讨论】:

  • 您的混淆使代码混乱。为什么查询字段yyyy,选择索引xxxx?也检查所有其他重命名。
  • 嘿@SergioTulentsev 请立即查看
  • 现在同样令人困惑。为什么键是xxx,但选定的索引在id 上?那些索引界限,真的是你得到的吗?
  • 嘿@SergioTulentsev 我认为现在很清楚了,我认为由于排序而采用了 id 索引,是的,我得到了相同的索引范围
  • 你有tenant_id的索引吗?

标签: database mongodb nosql aggregation-framework


【解决方案1】:

要正确支持此查询,您需要在{tenant_id: 1, id: -1} 上建立一个复合索引。第一部分帮助过滤,第二部分帮助对过滤结果进行快速排序。

一些文档:https://docs.mongodb.com/manual/core/index-compound/#sort-order

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-25
    • 2023-02-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多