为什么collections.find({})对250个对象占用超过9秒(MongoMapper)

ABr*_*wne 5 ruby mongodb mongomapper ruby-on-rails-3

我正在运行以下查询,返回结果平均需要9秒.它上面没有过滤器,所以我不确定索引是否会有所帮助.为什么这么慢?那里只有250个对象,只有4个字段(全部是文本).

Country.collection.find({},:fields => ['country_name', 'country_code']).to_json

"cursor":"BasicCursor",
"nscanned":247,
"nscannedObjects":247,
"n":247,
"millis":0,
"nYields":0,
"nChunkSkips":0,
"isMultiKey":false,
"indexOnly":false,
"indexBounds":{},
"allPlans":[{"cursor":"BasicCursor","indexBounds":{}}]
Run Code Online (Sandbox Code Playgroud)

机器上的cpu,内存和磁盘甚至都没有注意到查询运行.任何帮助,将不胜感激.

mon*_*top 3

使用以下命令在“country_name”字段上创建索引:

db.countries.ensureIndex({country_name:1});
Run Code Online (Sandbox Code Playgroud)

这将极大地加快您的查询速度您可以在此处了解有关索引的更多信息

PS-当您看到“has more”短语时,您可以输入“it”来显示更多内容,或者您​​可以使用以下命令显示所有结果而不显示“has more”:

db.countries.find({}, {'country_name' : 1, 'country_code' : 1}).forEach(printjson)
Run Code Online (Sandbox Code Playgroud)

您始终可以使用以下方法设置探查器:

>use databaseName;
> db.setProfilingLevel(2); // 2 tell the profiler to catch everything happened inside the DB
Run Code Online (Sandbox Code Playgroud)

您可以在此处了解有关探查器的更多信息

您可以使用以下命令在分析器中显示数据

> db.system.profile.find()
Run Code Online (Sandbox Code Playgroud)

此方法将为您提供有关数据库及其内部情况的更多信息。

  • 遗憾的是没有,但事实证明不是 mongo,而是 ruby​​ 驱动程序和 to_json 导致速度变慢。我最终缓存了 json 结果,效果非常好。现在整个ajax调用在70ms内完成端到端 (4认同)
  • 谢谢,在 shell 中运行 db.countries.find({}, {'country_name' : 1, 'country_code' : 1}).forEach(printjson) 会在几毫秒内执行并返回所有结果,正如我期望 mongo 那样。我将在我的 ruby​​ 堆栈上安装一个探查器,看看是什么导致了应该在几毫秒内执行的查询(在几秒钟内执行)。 (3认同)