Not In queries in Rails with MongoDB and Mongoid

Jan 9 2018

Sometimes you want a quick “not in” or “not equal” query in Rails, but you’re running Mongo. ActiveRecord allows us to write where.not against relational databases, but this doesn’t work when using Mongoid. Instead, you can use nin or it’s alias not_in

Book.not_in(title: "Of mice and men")

The method is also chainable, so this is valid:

Book.where(author: "Steinbeck").not_in(title: "Of mice and men")

If you prefer not to chain your methods, you can also write the query by sending nin to a symbolised version of your model’s property and then using the old hashrocket syntax to specify the value:

Book.where(author: "Steinbeck", :title.nin => ["Of mice and men"])