Hey there, fellow Ruby enthusiast! Ready to dive into the world of MongoDB? You're in for a treat. MongoDB's flexible document model and powerful query language make it a fantastic choice for many applications. In this guide, we'll walk through integrating MongoDB's API into your Ruby project. Let's get our hands dirty!
Before we jump in, make sure you've got:
First things first, let's get connected. Add the MongoDB Ruby driver to your Gemfile:
gem 'mongo'
Now, let's establish that connection:
require 'mongo' client = Mongo::Client.new('mongodb://localhost:27017/your_database')
Easy peasy, right? You're now ready to start slinging documents like a boss.
Time to populate that database:
collection = client[:users] result = collection.insert_one({ name: 'John Doe', email: '[email protected]' }) puts "Inserted #{result.n} document(s)"
Let's fetch that data back:
user = collection.find({ name: 'John Doe' }).first puts user
Need to make changes? We've got you covered:
result = collection.update_one({ name: 'John Doe' }, { '$set' => { email: '[email protected]' } }) puts "Modified #{result.n} document(s)"
Sometimes, you just gotta let go:
result = collection.delete_one({ name: 'John Doe' }) puts "Deleted #{result.n} document(s)"
Now, let's flex those MongoDB muscles with some advanced queries:
# Find users older than 30, sort by name results = collection.find({ age: { '$gt' => 30 } }).sort({ name: 1 }).limit(10) # Aggregation pipeline pipeline = [ { '$match' => { age: { '$gt' => 30 } } }, { '$group' => { _id: '$city', total: { '$sum' => 1 } } } ] results = collection.aggregate(pipeline)
Indexing: because ain't nobody got time for slow queries.
collection.indexes.create_one({ name: 1 }) collection.indexes.create_one({ email: 1 }, { unique: true })
Always be prepared:
begin # Your MongoDB operations here rescue Mongo::Error::SocketError puts "Couldn't connect to the database. Is it running?" rescue Mongo::Error::OperationFailure => e puts "Operation failed: #{e.message}" end
Keep those results manageable:
page = 1 per_page = 20 collection.find.skip((page - 1) * per_page).limit(per_page)
For when you need that ACID goodness:
session = client.start_session session.with_transaction do collection1.insert_one({ name: 'Alice' }, session: session) collection2.insert_one({ name: 'Bob' }, session: session) end
Don't forget to test! Here's a quick RSpec example:
RSpec.describe 'MongoDB Integration' do let(:client) { Mongo::Client.new('mongodb://localhost:27017/test_db') } let(:collection) { client[:users] } it 'inserts a document' do expect { collection.insert_one({ name: 'Test User' }) }.to change { collection.count_documents }.by(1) end end
When you're ready to ship:
And there you have it! You're now armed and dangerous with MongoDB knowledge. Remember, with great power comes great responsibility – use your newfound skills wisely. Happy coding, and may your queries be ever swift!