使用sort增加MongoDB性能

时间:2017-06-14 20:06:03

标签: mongodb performance aggregation-framework

我有一个拥有超过2000万条记录的集合:

{
  "_id" : ObjectId("58f8af0f65fc0a38e40a478f"),
  "text" : "Example text",
  "postdate" : NumberLong("1492692751921"),
  "cId" : "58e3cdbe29c8a54394c52c74",
}

这样的索引:{postdate : -1}

当然还有更多的领域,但这是最重要的。现在我想查询它:

db.coll.aggregate([
  { "$match" : { 
    "$and" : [ 
      { "postdate" : { "$gt" : 0}} , 
      { "postdate" : { "$lt" : 1497469601983}} , 
      { "cId" : "58e3cdbe29c8a54394c52c74"}
    ]
  }},
  { "$sort" : { "postdate" : -1}},
  { "$limit" : 20}]);

但这需要很长时间。我想知道我是否可以提高这种性能。我需要这个查询才能更快地运行。我该怎么办?

谢谢

1 个答案:

答案 0 :(得分:2)

尝试创建索引:

{ "cId" : 1, "postdate" : 1 }

此索引将索引$ match阶段中包含的两个字段,同时也为排序结果建立索引。有关索引索引的更多信息可以在here找到。

您可能还想通过运行一些解释计划来检查性能。 The response to this question包含有关如何对聚合执行说明的指南。

相关问题