【问题标题】:Increase MongoDB perfomance with sort通过排序提高 MongoDB 性能
【发布时间】:2017-06-14 20:06:02
【问题描述】:

我有一个包含超过 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}]);

但这需要很长时间。我想知道我是否可以提高这个性能。我需要这个查询更快地工作。我能做什么?

谢谢

【问题讨论】:

  • 你为什么在这里使用聚合,这之后你还有什么想做的吗?在"postdate" 上放置一个索引,但也可以使用常规查询进行测试。还假设您的 "postdate" 字段表示自纪元以来的毫秒数,那么您的值也不可能低于 0,因此应该隐含下边界。 .find({ "postdate": { "$lt" : 1497469601983 }, "cId" : "58e3cdbe29c8a54394c52c74" }).sort({ "postdate": -1 }).limit(1)。最重要的是,不要在不需要的地方使用$and。除非另有明确说明,否则所有 MongoDB 查询表达式都是已经 AND 参数。
  • 嗨 user6586661;如果您有性能问题,那么您的第一步应该是使用explain functions 查看服务器用于您的查询的查询计划,以及每个查询阶段需要多长时间。这将帮助您确定它在哪里运行缓慢,并告知您可能的更改选择。

标签: mongodb performance aggregation-framework


【解决方案1】:

尝试创建索引:

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

此索引将索引 $match 阶段中包含的两个字段,同时也索引排序结果。有关排序索引的更多信息,请访问here。

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

【讨论】:

  • 谢谢,cId 上的索引有效。但我在 postdate 上使用了索引 -1。
猜你喜欢
  • 2017-03-27
  • 1970-01-01
  • 2021-01-13
  • 1970-01-01
  • 2014-11-25
  • 1970-01-01
  • 2021-12-15
  • 1970-01-01
  • 2011-05-18
相关资源
最近更新 更多