【问题标题】:MongoDB index not used when sorting, although prefix matches排序时未使用 MongoDB 索引,尽管前缀匹配
【发布时间】:2019-07-02 12:55:36
【问题描述】:

我正在尝试以最有效的方式从 MongoDB 获取一组记录,但是当我向管道添加排序阶段时它出错了。服务器没有使用我想要的索引。然而,根据文档,它应该匹配前缀: https://docs.mongodb.com/manual/tutorial/sort-results-with-indexes/#sort-and-non-prefix-subset-of-an-index

我有一个如下所示的索引:

{
    "v" : 2,
    "key" : {
        "account_id" : 1,
        "cdr_block" : 1,
        "billing.total_billed" : 1,
        "times.created" : -1 
     },
     "name" : "IDX_by_account_and_block_sorted"
}

所以我假设当我过滤account_idcdr_blockbilling.total_billed,然后对times.created 进行排序时,将使用索引。

但事实并非如此;当我在 MongoDB shell 中检查查询解释时; 这个不使用索引,而是使用一个只由times.created组成的索引,所以需要几分钟:

db.getCollection("cdr").aggregate(
    [
        { 
            "$match" : {
                "account_id" : 160.0, 
                "cdr_block" : ObjectId("5d11e0364f853f15824aff47"), 
                "billing.total_billed" : {
                    "$gt" : 0.0
                }
            }
        }, 
        { 
            "$sort" : {
                "times.created" : -1.0
            }
        }
    ], 
    { 
        "allowDiskUse" : true
    }
);

如果我省略了 $sort 阶段,它确实会使用我上面提到的索引。

我在想这可能是因为它是一个聚合,但是这个“常规”查询也不使用索引:

db.getCollection("cdr").find({ 
    "account_id" : 160.0, 
    "cdr_block" : ObjectId("5d11e0364f853f15824aff47"), 
    "billing.total_billed" : {
        "$gt" : 0.0
    }
}).sort({"times.created" : -1 });

【问题讨论】:

    标签: mongodb mongodb-indexes


    【解决方案1】:

    $sort Operator and Performance

    $sort 运算符可以在放置在管道的开头或放置在 $project、$unwind 和 $group 聚合运算符之前时利用索引。如果 $project、$unwind 或 $group 发生在 $sort 操作之前, $sort 不能使用任何索引。

    【讨论】:

      猜你喜欢
      • 2020-05-11
      • 1970-01-01
      • 2012-11-11
      • 2012-01-16
      • 2021-10-21
      • 1970-01-01
      • 1970-01-01
      • 2020-01-20
      • 2014-12-21
      相关资源
      最近更新 更多