MongoID Lessons Learned

I am using MongoID to access MongoDB from a Ruby on Rails application. It is a good library. But there are some things I found out during the project, I want to share here. Nothing bad. Just some behaviors should now about.

Case Insensitive Search
There are different ways to write queries with MongoID. One pretty cool feature is that you can use regex for you queries. If you want to have all users who are starting with “mike”, you can write something like this:

query = User.where(name: /^#{name}/)

That is very useful. You can also make easily a case insensitive search by adding a “i” to the end of the regex.

query = User.where(name: /^#{name}/i)

Very useful feature. But you should know that the case insensitive search is 50% slower than the default regex search. At least that is what I measured. Funny that such a small “i” can have such a big impact 🙂

One fast workaround is to store the names twice. One times regular and one times lowercased. In that way you can execute the fast query on the lowercased column and in the UI you can show the normal name.

Returning an Empty Query
Sometimes you want to build together a criteria object dynamically. And sometimes it happens that you just return an empty criteria object. Something like this here:

Mongoid::Criteria.new(User)

I don’t know why but I assumed that this would return an empty criteria list with 0 users. But indeed it is a empty criteria and it returns all users from the Database 🙂

This is the code which returns really 0 users:

Mongoid::Criteria.new(User, {_id: -1})

This is a criteria object with the constraint “_id = -1”. And because there is no object in the collection with ID equal -1 it returns 0 Users.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s