At the Forge - MongoDB

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

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' => 'reuven@lerner.co.il'})
=> 4b6ff0693c1c7d6ecd000001

you can retrieve the IDs as follows:

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

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}
OrderedHash
OrderedHash

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'] }  }
                       ).count
=> 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.

Conclusion

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.

______________________

White Paper
Linux Management with Red Hat Satellite: Measuring Business Impact and ROI

Linux has become a key foundation for supporting today's rapidly growing IT environments. Linux is being used to deploy business applications and databases, trading on its reputation as a low-cost operating environment. For many IT organizations, Linux is a mainstay for deploying Web servers and has evolved from handling basic file, print, and utility workloads to running mission-critical applications and databases, physically, virtually, and in the cloud. As Linux grows in importance in terms of value to the business, managing Linux environments to high standards of service quality — availability, security, and performance — becomes an essential requirement for business success.

Learn More

Sponsored by Red Hat

White Paper
Private PaaS for the Agile Enterprise

If you already use virtualized infrastructure, you are well on your way to leveraging the power of the cloud. Virtualization offers the promise of limitless resources, but how do you manage that scalability when your DevOps team doesn’t scale? In today’s hypercompetitive markets, fast results can make a difference between leading the pack vs. obsolescence. Organizations need more benefits from cloud computing than just raw resources. They need agility, flexibility, convenience, ROI, and control.

Stackato private Platform-as-a-Service technology from ActiveState extends your private cloud infrastructure by creating a private PaaS to provide on-demand availability, flexibility, control, and ultimately, faster time-to-market for your enterprise.

Learn More

Sponsored by ActiveState