1

I'm using MongoDB (with Mongoid) have a query which runs really really often in my app, I'm not sure I have proper indexes set up to make the queries more efficient, here is a snippet from my log when the query runs:

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 ...

How could I make this more efficient, or is the behavior I'm seeing typical?

Update

So the way I'm getting these records is via these scopes:

scope :active, where(:active => true)
default_scope order_by([:created_at, :desc])

Then I set the instance varibale in my controller thusly:

@users = User.active
Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
JP Silvashy
  • 46,977
  • 48
  • 149
  • 227

1 Answers1

1

This appears to be an N+1 problem and you can fix it by using eager loading. An explanation of eager loading in Mongo for mongo mapper can be found here (search for "Eager Loading"):

Kevin Sylvestre
  • 37,288
  • 33
  • 152
  • 232