require 'mongo/driver'Enhancements for MongoDB Ruby Driver.
Lower layers are independent from upper, use only what You need.
Install mongodb with Rubygems:
gem install mongodb
Once installed, You can proceed with the examples.
The project is [hosted on GitHub][project]. You can report bugs and discuss features on the [issues page][issues].
MongoDB itself is very powerful, flexible and simple tool, but the API of the Ruby Driver is a little complicated.
These enhancements carefully alter Driver's API and made it more simple and intuitive (but still 100% backward compatible).
Requiring driver enhancements.
require 'mongo/driver'Changing some defaults (optional, don't do it if You don't need it).
By default they are set to false to provide maximum performance, but if You use MongoDB as major application database (and not only for logging, andalytics and other minor tasks) it's usually better to set it to true.
Mongo.defaults.merge! multi: true, safe: trueConnecting to test database and cleaning it before starting the sample.
connection = Mongo::Connection.new
db = connection.default_test
db.dropCollection shortcuts, access collection directly by typing its name,
instead of db.collection('some_collection').
db.some_collectionLet's create two Heroes.
db.units.save name: 'Zeratul'
db.units.save name: 'Tassadar'Querying first and all documents matching criteria (there's
also :each method, the same as :all).
p db.units.first(name: 'Zeratul') # => zeratul
p db.units.all(name: 'Zeratul') # => [zeratul]
db.units.all name: 'Zeratul' do |unit|
p unit # => zeratul
endDynamic finders, handy way to do simple queries.
p db.units.by_name('Zeratul') # => zeratul
p db.units.first_by_name('Zeratul') # => zeratul
p db.units.all_by_name('Zeratul') # => [zeratul]Bang versions, will raise error if nothing found.
p db.units.first!(name: 'Zeratul') # => zeratul
p db.units.by_name!('Zeratul') # => zeratulQuery sugar, use :_gt instead of :$gt. It's more convinient to use new hash
syntax {name: {_gt: 'Z'}} instead of hashrockets {name: {:$gt => 'Z'}}.
Mongo.defaults[:convert_underscore_to_dollar] = true
p db.units.all(name: {_gt: 'Z'}) # => [zeratul]In this example we covered enhancements of MongoDB Ruby Driver, if You are interesting You can also take a look at Data Migration and Persistence for Ruby Objects examples.