🔍Lazy Loading in Mongoid: Understanding Mongoid::Criteria

Austin PremodAustin Premod
2 min read

When working with Mongoid (MongoDB ORM for Rails), you might write something like:

likes = Like.where(user: user)

At first glance, you might think this line runs a database query immediately. But, surprise, it doesn’t. In this post, we’ll unpack what’s happening behind the scenes with Mongoid::Criteria, how lazy loading works, and why it’s a performance-friendly feature you should love.

đź§  What is Mongoid::Criteria?

When you call:

likes = Like.where(user: user)

You're not retrieving any data yet. Instead, you get back an Mongoid::Criteria object, essentially a blueprint for the query.

puts likes.class
=> Mongoid::Criteria

This object describes what to fetch from the database, but Mongoid delays the actual DB call until it’s truly needed. This is what we mean by lazy loading.

🚀 When Does the Query Run?

The query only hits the database when something in your code forces evaluation. Common triggers include:

  • .to_a

  • .first

  • .each

  • .map

  • .count

  • .pluck

likes = Like.where(user: user) # Still just a query object
likes.each do |like|
puts like.likeable_type
end
=> Now the DB query actually runs here

⚙️ Why Lazy Loading Is Powerful

Lazy loading might feel a little magical at first, but it offers some serious benefits:

âś… Performance-friendly: Avoids unnecessary DB hits while you build your query
âś… Flexible: Chain additional conditions or scopes before executing
âś… Predictable (once you know it): Debugging gets easier when you understand the query lifecycle

đź§Ş How to See the Actual DB Query (Optional Debugging)

If you want to see exactly when the query runs, you can monitor your logs.

Rails.logger = Logger.new($stdout)
Rails.logger.level = 0
Mongo::Logger.logger= Rails.logger

Or you can just monitor your logs.

tail -f log/development.log

đź§µ Wrap-up

Lazy loading isn’t unique to Mongoid—it’s a common pattern in many ORMs (ActiveRecord does it too). But understanding when your query runs is crucial for writing performant and bug-free code.

0
Subscribe to my newsletter

Read articles from Austin Premod directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Austin Premod
Austin Premod