At the Forge - MongoDB

A look at one of the best-known contenders in the non-relational database space.

The find_one method, as you have seen, returns a single element from a collection. A similar find method returns all of the elements using the Enumerable module, allowing you to iterate over all of the documents in a collection using each. For example, if you add another document:

irb(main):026:0> c.insert({'name' => 'Reuven',
                           'email_address' => ''})
=> 4b6ff0693c1c7d6ecd000001

you can retrieve the IDs as follows:

irb(main):030:0> c.find.each {|i| puts i['_id']}

Notice how you can pull out the _id column by treating the document as a hash. Indeed, if you ask Ruby to show the class of the object, rather than its ID, this suspicion is confirmed:

irb(main):031:0> c.find.each {|i| puts i.class}

But, perhaps you're interested only in some of the documents. By invoking find with a hash, it will return only those documents that match the contents of your hash. For example:

irb(main):040:0> c.find({'name' => 'Reuven'}).count
=> 1

If nothing matches the hash that you passed, you will get an empty result set:

irb(main):041:0> c.find({'name' => 'Reuvennn'}).count
=> 0

You also can search for regular expressions:

irb(main):042:0> c.find({'name' => /eu/}).count
=> 1

irb(main):043:0> c.find({'name' => /ez/}).count
=> 0

By passing a hash as the value for a key, you also can modify the query, passing parameters that define MongoDB's query syntax. These query operators all begin with the dollar sign ($) and are passed as the key to a sub-hash. For example, you can retrieve all of the documents whose “name” is one of the values in a specified array, as follows:

irb(main):049:0> c.find({'name' =>
                           {'$in' => ['Reuven', 'Atara', 'Shikma',
 ↪'Amotz'] }  }
=> 1

You also can sort the results by invoking the sort method on the result set, using a similar syntax:

irb(main):049:0> c.find({'name' =>
                           {'$in' => ['Reuven', 'Atara', 'Shikma',
 ↪'Amotz'] }  }
                       ).sort({"name" => 1})

Just as you can sort a result set, you also can perform other actions on it that are analogous to several relational counterparts, such as grouping and limiting the number of results. If you are used to a functional style of programming, in which you chain a number of methods to one another, this style easily will lend itself to working with MongoDB.


MongoDB is causing many ripples in the open-source and database worlds because of its high performance and easy learning curve. This month, I covered the basics of installing and working with MongoDB. Next month, I'll look at some more-advanced topics, such as indexing (which makes queries execute much faster), embedding objects in one another and referencing objects across collections.

Reuven M. Lerner is a longtime Web developer, trainer, and consultant. He is a PhD candidate in Learning Sciences at Northwestern University. Reuven lives with his wife and three children in Modi'in, Israel.


Geek Guide
The DevOps Toolbox

Tools and Technologies for Scale and Reliability
by Linux Journal Editor Bill Childers

Get your free copy today

Sponsored by IBM

8 Signs You're Beyond Cron

Scheduling Crontabs With an Enterprise Scheduler
On Demand
Moderated by Linux Journal Contributor Mike Diehl

Sign up and watch now

Sponsored by Skybot