driver.rb |
|
|---|---|
|
Enhancements for MongoDB Ruby Driver.
Lower layers are independent from upper, use only what You need. Install mongodb with Rubygems:
Once installed, You can proceed with the examples. The project is hosted on GitHub. You can report bugs and discuss features on the issues page. |
|
Driver exampleMongoDB 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: true |
|
Connecting to test database and cleaning it before starting the sample. |
connection = Mongo::Connection.new
db = connection.default_test
db.drop |
|
Collection shortcuts, access collection directly by typing its name,
instead of |
db.some_collection |
|
Let’s create two Heroes. |
db.units.save name: 'Zeratul'
db.units.save name: 'Tassadar' |
|
Querying first and all documents matching criteria (there’s
also |
p db.units.first(name: 'Zeratul') # => zeratul
p db.units.all(name: 'Zeratul') # => [zeratul]
db.units.all name: 'Zeratul' do |unit|
p unit # => zeratul
end |
|
Dynamic 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') # => zeratul |
|
Query sugar, use |
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. |
|