通过排序提高MongoDB的性能 [英] Increase MongoDB perfomance with sort

查看:212
本文介绍了通过排序提高MongoDB的性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的馆藏中有超过2000万条这样的记录:

I have a collection with over 20 million records like this:

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

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

当然还有更多字段,但这是最重要的。现在我要这样查询:

Of course are there more fields, but this are the most important. Now I want to query for it like this:

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

但这需要一段时间。我想知道是否可以提高此性能。我需要此查询才能更快地工作。我该怎么办?

But this takes ages. I am wondering if I can increase this performance. I need this query to work faster. What can I do?

谢谢

推荐答案

尝试创建索引:

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

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

This index will index both fields contained in the $match stage while also indexing for the sort results. More information about indexing for sorts can be found here.

您可能还想通过运行一些解释计划来检查性能。 对此问题的回答包含有关如何对广告进行解释的指南聚合。

You might also want to examine performance by running some explain plans. The response to this question contains a guide on how to perform an explain on an aggregation.

这篇关于通过排序提高MongoDB的性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆