稀疏索引不能改善MongoDB中的排序?

时间:2019-01-17 06:28:23

标签: mongodb sorting indexing mongodb-query

我的收藏中有超过10万个文档。 样本文档就像

{ 
    "created_at" : 1545039649, 
    "priority" : 3, 
    "id" : 68, 
    "name" : "document68"
}


db.mycol.find().sort({created_at:1})

db.mycol.find().sort({priority:1})

导致错误。

Error: error: {
    "ok" : 0,
    "errmsg" : "Executor error during find command: OperationFailed: Sort operation used more than the maximum 33554432 bytes of RAM. Add an index, or specify a smaller limit.",
    "code" : 96,
    "codeName" : "OperationFailed"
}

然后我将这些字段编入索引。

db.mycol.createIndex({'priority':1})
db.mycol.createIndex({'created_at':1}, {sparse:true})

将稀疏索引添加到 created_at ,因为它是必填字段。

现在

db.mycol.find().sort({priority:1})

给出结果。但是

db.mycol.find().sort({created_at:1})

仍然导致相同的错误。

1 个答案:

答案 0 :(得分:1)

仅当您用created_at: {$exists: true}过滤时,才能使用稀疏索引。

原因是所有其他记录都不是索引的一部分(但它们仍应该出现在结果中-可能在末尾)。

也许您不必使索引稀疏(仅当大多数记录没有该字段时才有意义-否则无论如何您都不会在索引存储中节省太多空间)? created_at听起来像大多数记录都会有它。

  

将稀疏索引添加到created_at,因为它是必填字段。

实际上,这是另一回事:当字段是可选的(并且非常罕见)时,您只需要稀疏索引。