我正在使用MongoDB(使用Mongoid)有一个查询,它经常在我的应用程序中运行,我不确定我是否设置了适当的索引以提高查询效率,这里是我日志中的一个片段查询运行:
MONGODB (33ms) recipes_development['system.namespaces'].find({})
MONGODB (6ms) recipes_development['recipes'].find({})
MONGODB (0ms) recipes_development['system.namespaces'].find({})
MONGODB (0ms) recipes_development['users'].find({:_id=>BSON::ObjectId('4f48469d4064241d860002d9')}).limit(-1).sort([[:created_at, :desc]])
MONGODB (0ms) recipes_development['users'].find({:_id=>BSON::ObjectId('4f48469d4064241d8600032a')}).limit(-1).sort([[:created_at, :desc]])
MONGODB (0ms) recipes_development['users'].find({:_id=>BSON::ObjectId('4f48469a4064241d8600008d')}).limit(-1).sort([[:created_at, :desc]])
MONGODB (0ms) recipes_development['users'].find({:_id=>BSON::ObjectId('4f48469c4064241d86000273')}).limit(-1).sort([[:created_at, :desc]])
MONGODB (0ms) recipes_development['users'].find({:_id=>BSON::ObjectId('4f48469d4064241d86000365')}).limit(-1).sort([[:created_at, :desc]])
MONGODB (0ms) recipes_development['users'].find({:_id=>BSON::ObjectId('4f4846a34064241d86000910')}).limit(-1).sort([[:created_at, :desc]])
MONGODB (0ms) recipes_development['users'].find({:_id=>BSON::ObjectId('4f48499a4064241c58000027')}).limit(-1).sort([[:created_at, :desc]])
MONGODB (0ms) recipes_development['users'].find({:_id=>BSON::ObjectId('4f48499a4064241c58000027')}).limit(-1).sort([[:created_at, :desc]])
MONGODB (0ms) recipes_development['users'].find({:_id=>BSON::ObjectId('4f48499a4064241c58000027')}).limit(-1).sort([[:created_at, :desc]])
... many more ...
我怎样才能提高效率,或者是我看到的典型行为?
的更新 的
所以我获取这些记录的方式是通过以下范围:
scope :active, where(:active => true)
default_scope order_by([:created_at, :desc])
然后我在控制器中设置实例varibale:
@users = User.active
答案 0 :(得分:1)
这似乎是一个N + 1问题,你可以通过使用预先加载来修复它。可以在此处找到Mongo for mongo mapper中急切加载的解释(搜索“Eager Loading”):