Our great sponsors
-
InfluxDB
Power Real-Time Data Analytics at Scale. Get real-time insights from all types of time series data with InfluxDB. Ingest, query, and analyze billions of data points in real-time with unbounded cardinality.
# # mongoid_n_plus_1.rb # require 'benchmark' require 'bundler/inline' gemfile do source 'https://rubygems.org' gem 'mongoid' gem 'mongo' end Mongoid.configure do |config| config.clients.default = { uri: "mongodb://localhost:27017,localhost:27018,localhost:27019/test" } end class Test include Mongoid::Document field :name, type: String # return all entries from the document that aren't defined as Mongoid fields def entries attr = self.attributes.dup attr.delete_if { |k, v| self.fields.key?(k) } attr.sort end def compact! # unset each field that doesn't belong to the Mongoid document as an # explicitly defined field self.entries.each do |entry| self.unset entry.first end end end
To address this Rails offers Eager Loading Associations and there are gems (such as bullet) that can be used to detect the N + 1 pattern in an application.
First, we spin up a local replica set using some open source MongoDB helper utilities (see m and mtools):