MongoDB 排序时不使用索引,尽管前缀匹配
MongoDB index not used when sorting, although prefix matches
我正在尝试以最有效的方式从 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_id
、cdr_block
和 billing.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 阶段,它会使用我上面提到的索引。
我在想这可能是因为它是一个聚合,但是这个 'regular' 查询也没有使用索引:
db.getCollection("cdr").find({
"account_id" : 160.0,
"cdr_block" : ObjectId("5d11e0364f853f15824aff47"),
"billing.total_billed" : {
"$gt" : 0.0
}
}).sort({"times.created" : -1 });
$sort Operator and Performance
$sort 运算符放在管道的开头或放在 $project、$unwind 和 $group 聚合运算符之前可以利用索引。如果 $project、$unwind 或 $group 在 $sort 操作之前发生,
$sort 不能使用任何索引。
我正在尝试以最有效的方式从 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_id
、cdr_block
和 billing.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 阶段,它会使用我上面提到的索引。
我在想这可能是因为它是一个聚合,但是这个 'regular' 查询也没有使用索引:
db.getCollection("cdr").find({
"account_id" : 160.0,
"cdr_block" : ObjectId("5d11e0364f853f15824aff47"),
"billing.total_billed" : {
"$gt" : 0.0
}
}).sort({"times.created" : -1 });
$sort Operator and Performance
$sort 运算符放在管道的开头或放在 $project、$unwind 和 $group 聚合运算符之前可以利用索引。如果 $project、$unwind 或 $group 在 $sort 操作之前发生, $sort 不能使用任何索引。