### UserRepository with Container-Friendly Instance Methods Source: https://context7.com/flagman/mongo_one/llms.txt This example shows a UserRepository class designed for dependency injection and testing. It uses instance methods to interact with a user collection, demonstrating methods for finding users by email, creating users, and retrieving active users. It also includes a MockUserRepository for testability. ```ruby class UserRepository attr_reader :collection def initialize @collection = User.new end def find_by_email(email) @collection.find({ email: email }).one end def create_user(attributes) @collection.insert_one(attributes) end def active_users @collection.find({ active: true }).all end end # Use in application user_repo = UserRepository.new user = user_repo.find_by_email('alice@example.com') # Easy to mock in tests class MockUserRepository < UserRepository def find_by_email(email) User::Struct.new(name: 'Test User', email: email) end end ``` -------------------------------- ### Define Product Schema with MongoOne and Dry::Struct Source: https://context7.com/flagman/mongo_one/llms.txt This snippet demonstrates defining a product schema using MongoOne's integration with Dry::Struct. It includes various attribute types like String, Float, Integer, Bool, Array, Hash, optional types, and constrained types. The example also shows struct initialization with BSON::ObjectId. ```ruby class Product include MongoOne schema :products do attribute :name, Types::String attribute :price, Types::Float attribute :quantity, Types::Integer attribute :active, Types::Bool attribute :tags, Types::Array.of(Types::String) attribute :metadata, Types::Hash # Optional types (can be nil) attribute :description, Types::String.optional attribute :discount, Types::Float.optional # _id with Types::Any for BSON::ObjectId handling attribute :_id, Types::Any # Constrained types attribute :rating, Types::Integer.constrained(gteq: 0, lteq: 5) end end # Types automatically validate on struct initialization product = Product::Struct.new( _id: BSON::ObjectId.new, name: 'Widget', price: 19.99, quantity: 100, active: true, tags: ['sale', 'featured'], metadata: { color: 'blue' } ) ``` -------------------------------- ### Configure and Connect to MongoDB with MongoOne Source: https://context7.com/flagman/mongo_one/llms.txt Sets up the MongoDB connection parameters, establishes the connection, and provides methods to access collections and close the connection. It requires the 'mongo_one' gem. ```ruby require 'mongo_one' # Configure database connection MongoOne::Db.configure( database: 'my_app_production', addr: 'localhost:27017', max_pool_size: 10, read_mode: :primary ) # Establish connection MongoOne::Db.establish_connection # Access collections directly MongoOne::Db[:users].find({ active: true }).to_a # Close connection when done MongoOne::Db.close_connection ``` -------------------------------- ### Database Configuration Source: https://context7.com/flagman/mongo_one/llms.txt Configure and establish a connection to your MongoDB database. You can set database name, host address, connection pool size, and read preferences. The connection can be closed when no longer needed. ```APIDOC ## Database Configuration ### Description Configure MongoDB connection parameters including host, database name, and connection pool settings. Establish and close the connection as needed. ### Method N/A (Configuration and connection management) ### Endpoint N/A ### Parameters N/A ### Request Example ```ruby require 'mongo_one' # Configure database connection MongoOne::Db.configure( database: 'my_app_production', addr: 'localhost:27017', max_pool_size: 10, read_mode: :primary ) # Establish connection MongoOne::Db.establish_connection # Access collections directly MongoOne::Db[:users].find({ active: true }).to_a # Close connection when done MongoOne::Db.close_connection ``` ### Response N/A ``` -------------------------------- ### Index Management in MongoDB with Ruby Source: https://context7.com/flagman/mongo_one/llms.txt Details how to define and automatically manage MongoDB indexes using the `MongoOne::AutoIndex` module, including inline schema definition and synchronization. ```ruby class User include MongoOne schema :users do attribute :email, Types::String attribute :username, Types::String attribute :age, Types::Integer attribute :created_at, Types::Integer # Define indexes inline with schema indexes do index :email_unique, keys: { email: 1 }, options: { unique: true } index :username_idx, keys: { username: 1 } index :age_created_compound, keys: { age: -1, created_at: -1 }, options: { sparse: true } end end end # Apply indexes to database (creates, updates, or drops as needed) MongoOne::AutoIndex.apply_indexes # Fetch existing indexes for a collection indexes = MongoOne::AutoIndex.fetch_existing_indexes(User) # => [{"name"=>"email_unique", "key"=>{"email"=>1}, "unique"=>true}, ...] ``` -------------------------------- ### Batch Processing Large Datasets in Ruby Source: https://context7.com/flagman/mongo_one/llms.txt Illustrates efficient batch processing of MongoDB documents using `each_batch` with customizable fetch and yield sizes, including streaming and with index. ```ruby # Process 10,000 documents in batches of 100 User.find({ active: true }) .sort({ created_at: 1 }) .limit(10_000) .each_batch(100) do |batch| # batch is an array of 100 User::Struct objects batch.each { |user| process_user(user) } end # Different fetch and batch sizes for fine control # Fetch 1000 at a time, yield in batches of 50 User.find .each_batch(1000, batch_size: 50) do |batch| BulkProcessor.process(batch) end # Process one document at a time (streaming) User.find.each_batch(500, batch_size: 1) do |user| # user is a single object, not an array EmailService.send_notification(user) end # With skip and limit User.find .skip(1000) .limit(5000) .each_batch(100, batch_size: 25) .with_index do |batch, index| puts "Processing batch #{index}: #{batch.size} records" end ``` -------------------------------- ### Execute MongoDB Aggregation Pipelines in Ruby Source: https://context7.com/flagman/mongo_one/llms.txt Shows how to define and execute MongoDB aggregation pipelines using Ruby, including custom result mapping with Dry::Struct. ```ruby # Define aggregation result struct class AgeStats < Dry::Struct transform_keys(&:to_sym) attribute :_id, Types::Integer attribute :count, Types::Integer attribute :avg_age, Types::Float.optional end # Execute aggregation pipeline pipeline = [ { '$match' => { active: true } }, { '$group' => { '_id' => '$age', 'count' => { '$sum' => 1 }, 'avg_age' => { '$avg' => '$age' } }}, { '$sort' => { count: -1 } }, { '$limit' => 10 } ] results = User.aggregate(pipeline).map_to(AgeStats).all results.each do |stat| puts "Age #{stat._id}: #{stat.count} users (avg: #{stat.avg_age})" end ``` -------------------------------- ### Timestamps Plugin for MongoDB Documents in Ruby Source: https://context7.com/flagman/mongo_one/llms.txt Explains the automatic management of `created_at` and `updated_at` timestamps on MongoDB documents using the `MongoOne` timestamps plugin. ```ruby class Post include MongoOne schema :posts do attribute :title, Types::String attribute :content, Types::String # Register timestamps plugin plugins do timestamps end end end # created_at and updated_at are automatically added to schema # and managed on insert/update operations # Create a post (timestamps added automatically) Post.insert_one(title: 'Hello World', content: 'First post') # Document: { title: 'Hello World', content: 'First post', # created_at: 1697648293847, updated_at: 1697648293847 } # Update a post (updated_at modified automatically) Post.update_one( { title: 'Hello World' }, { '$set' => { content: 'Updated content' } } ) # updated_at is automatically set to current timestamp # Touch multiple documents (update timestamp without other changes) Post.touch_many({ status: 'draft' }) ``` -------------------------------- ### Delete Documents in MongoDB with Ruby Source: https://context7.com/flagman/mongo_one/llms.txt Demonstrates how to delete multiple documents based on a condition and how to delete all documents in a collection. ```ruby # Delete multiple documents User.delete_many({ last_login: { '$lt' => Time.now - (365 * 86400) } }) # Delete all documents in collection User.delete_many({}) ``` -------------------------------- ### Query MongoDB Documents with MongoOne Source: https://context7.com/flagman/mongo_one/llms.txt Provides flexible methods for querying MongoDB collections, including finding single documents with strict error handling or optional returns, retrieving all matching documents, and applying sorting, skipping, and limiting. It also supports counting documents and using an options hash for queries. ```ruby # Find single document with strict error handling user = User.find({ email: 'alice@example.com' }).one! # Raises MongoOne::Errors::NotFoundError if not found # Find with optional return (returns nil if not found) user = User.find({ name: 'NonExistent' }).one # => nil # Find all matching documents active_users = User.find({ active: true }).all # => [#, #, ...] # Complex query with chaining results = User .find({ age: { '$gte' => 25 } }) .sort({ name: 1 }) .skip(10) .limit(20) .all # Count documents count = User.find({ age: { '$gte' => 18 } }).count # => 1543 # Query with options hash User.find({ email: 'test@example.com' }, { limit: 1, sort: { created_at: -1 } }).one ``` -------------------------------- ### Find and Query Operations Source: https://context7.com/flagman/mongo_one/llms.txt Execute flexible queries to find documents. Supports finding single or multiple documents, with options for strict error handling, optional returns, sorting, skipping, limiting, and counting. Automatic object mapping to Structs is included. ```APIDOC ## Find and Query Operations ### Description Execute flexible queries with sorting, skipping, limiting, and automatic object mapping. ### Method `GET` (conceptually, for retrieving data) ### Endpoint N/A (Operates on defined collection) ### Parameters N/A ### Request Example ```ruby # Find single document with strict error handling user = User.find({ email: 'alice@example.com' }).one! # Raises MongoOne::Errors::NotFoundError if not found # Find with optional return (returns nil if not found) user = User.find({ name: 'NonExistent' }).one # => nil # Find all matching documents active_users = User.find({ active: true }).all # => [#, #, ...] # Complex query with chaining results = User .find({ age: { '$gte' => 25 } }) .sort({ name: 1 }) .skip(10) .limit(20) .all # Count documents count = User.find({ age: { '$gte' => 18 } }).count # => 1543 # Query with options hash User.find({ email: 'test@example.com' }, { limit: 1, sort: { created_at: -1 } }).one ``` ### Response N/A ``` -------------------------------- ### Insert Documents into MongoDB with MongoOne Source: https://context7.com/flagman/mongo_one/llms.txt Handles insertion of single or multiple documents into MongoDB collections. It supports automatic type validation against defined schemas and integrates with plugin hooks. It also demonstrates a container-friendly instance method approach. ```ruby # Insert a single document User.insert_one( name: 'Alice Johnson', email: 'alice@example.com', age: 28, addresses: [ { street: '123 Main St', city: 'Boston', postal_code: '02101' } ], preferences: { theme: 'dark', notifications: true, settings: { sound_enabled: false } } ) # Insert multiple documents at once users = [ { name: 'Bob Smith', email: 'bob@example.com', age: 35 }, { name: 'Carol White', email: 'carol@example.com', age: 42 } ] User.insert_many(users) # Container-friendly instance method approach user_repo = User.new user_repo.insert_one(name: 'David Brown', email: 'david@example.com') ``` -------------------------------- ### Custom Projections with Dry::Struct in Ruby Source: https://context7.com/flagman/mongo_one/llms.txt Explains how to map MongoDB query results to custom Dry::Struct types, enabling automatic projection optimization and disabling it when necessary. ```ruby # Define a minimal struct for specific fields class UserSummary < Dry::Struct transform_keys(&:to_sym) attribute :_id, Types::Any attribute :name, Types::String attribute :email, Types::String end # Query with automatic projection (only fetches name and email) summaries = User.find({ active: true }).map_to(UserSummary).all # MongoDB projection: { name: 1, email: 1 } # Disable automatic projection if needed users = User.find.auto_project(false).map_to(UserSummary).all # Default mapping uses the collection's auto-generated Struct users = User.find.all # Maps to User::Struct ``` -------------------------------- ### Define Typed Schemas with Dry::Struct in MongoOne Source: https://context7.com/flagman/mongo_one/llms.txt Defines typed document schemas for MongoDB collections using Dry::Struct. This enables automatic struct generation, compile-time type checking, and supports nested structures, optional fields, and automatic handling of the `_id` field. ```ruby class User include MongoOne schema :users do # Basic attributes with types attribute :name, Types::String attribute :email, Types::String attribute :age, Types::Integer.optional # Nested array of hashes attribute :addresses, Types::Array do attribute :street, Types::String attribute :city, Types::String attribute? :postal_code, Types::String # Optional field (may be missing) end # Nested hash attribute :preferences, Types::Hash do attribute :theme, Types::String attribute :notifications, Types::Bool attribute :settings, Types::Hash do attribute :sound_enabled, Types::Bool end end # _id is automatically defined as Types::Any to handle BSON::ObjectId end end # The schema automatically creates User::Struct class user = User.find({ email: 'john@example.com' }).one puts user.name # => "John Doe" puts user.addresses.first.city # => "New York" ``` -------------------------------- ### Insert Operations Source: https://context7.com/flagman/mongo_one/llms.txt Insert single or multiple documents into a collection. Supports automatic type validation and plugin hooks. Can be used with class-level or instance-level methods. ```APIDOC ## Insert Operations ### Description Insert single or multiple documents with automatic type validation and plugin hooks. ### Method `POST` (conceptually, for inserting data) ### Endpoint N/A (Operates on defined collection) ### Parameters N/A ### Request Example ```ruby # Insert a single document User.insert_one( name: 'Alice Johnson', email: 'alice@example.com', age: 28, addresses: [ { street: '123 Main St', city: 'Boston', postal_code: '02101' } ], preferences: { theme: 'dark', notifications: true, settings: { sound_enabled: false } } ) # Insert multiple documents at once users = [ { name: 'Bob Smith', email: 'bob@example.com', age: 35 }, { name: 'Carol White', email: 'carol@example.com', age: 42 } ] User.insert_many(users) # Container-friendly instance method approach user_repo = User.new user_repo.insert_one(name: 'David Brown', email: 'david@example.com') ``` ### Response N/A ``` -------------------------------- ### Schema Definition Source: https://context7.com/flagman/mongo_one/llms.txt Define typed document schemas for your MongoDB collections using Dry::Struct. Supports basic types, optional fields, nested structures, and arrays of hashes. The schema automatically generates a corresponding Struct class for type-safe object mapping. ```APIDOC ## Schema Definition ### Description Define typed document schemas with nested structures, optional fields, and automatic struct generation. Uses Dry::Struct for type safety. ### Method N/A (Schema definition) ### Endpoint N/A ### Parameters N/A ### Request Example ```ruby class User include MongoOne schema :users do # Basic attributes with types attribute :name, Types::String attribute :email, Types::String attribute :age, Types::Integer.optional # Nested array of hashes attribute :addresses, Types::Array do attribute :street, Types::String attribute :city, Types::String attribute? :postal_code, Types::String # Optional field (may be missing) end # Nested hash attribute :preferences, Types::Hash do attribute :theme, Types::String attribute :notifications, Types::Bool attribute :settings, Types::Hash do attribute :sound_enabled, Types::Bool end end # _id is automatically defined as Types::Any to handle BSON::ObjectId end end # The schema automatically creates User::Struct class user = User.find({ email: 'john@example.com' }).one puts user.name # => "John Doe" puts user.addresses.first.city # => "New York" ``` ### Response N/A ``` -------------------------------- ### Delete Operations Source: https://context7.com/flagman/mongo_one/llms.txt Remove single or multiple documents from a collection based on specified criteria. ```APIDOC ## Delete Operations ### Description Remove single or multiple documents from the collection. ### Method `DELETE` (conceptually, for removing data) ### Endpoint N/A (Operates on defined collection) ### Parameters N/A ### Request Example ```ruby # Delete a single document User.delete_one({ email: 'old@example.com' }) ``` ### Response N/A ``` -------------------------------- ### Update Documents in MongoDB with MongoOne Source: https://context7.com/flagman/mongo_one/llms.txt Enables updating single or multiple documents in MongoDB using standard MongoDB update operators like '$set'. It supports updating nested fields, performing upserts, and utilizing aggregation pipelines for more complex update logic. ```ruby # Update a single document User.update_one( { email: 'alice@example.com' }, { '$set' => { age: 29, 'preferences.theme' => 'light' } } ) # Update multiple documents User.update_many( { age: { '$lt' => 18 } }, { '$set' => { minor: true } } ) # Update with options User.update_one( { name: 'New User' }, { '$set' => { email: 'new@example.com' } }, { upsert: true } ) # Update using aggregation pipeline User.update_many( { active: true }, [ { '$set' => { full_name: { '$concat' => ['$first_name', ' ', '$last_name'] } } } ] ) ``` -------------------------------- ### Update Operations Source: https://context7.com/flagman/mongo_one/llms.txt Update single or multiple documents in a collection using MongoDB update operators. Supports setting fields, using aggregation pipelines, and upsert operations. ```APIDOC ## Update Operations ### Description Update single or multiple documents using MongoDB update operators. ### Method `PUT` or `PATCH` (conceptually, for updating data) ### Endpoint N/A (Operates on defined collection) ### Parameters N/A ### Request Example ```ruby # Update a single document User.update_one( { email: 'alice@example.com' }, { '$set' => { age: 29, 'preferences.theme' => 'light' } } ) # Update multiple documents User.update_many( { age: { '$lt' => 18 } }, { '$set' => { minor: true } } ) # Update with options User.update_one( { name: 'New User' }, { '$set' => { email: 'new@example.com' } }, { upsert: true } ) # Update using aggregation pipeline User.update_many( { active: true }, [ { '$set' => { full_name: { '$concat' => ['$first_name', ' ', '$last_name'] } } } ] ) ``` ### Response N/A ``` -------------------------------- ### Delete Documents from MongoDB with MongoOne Source: https://context7.com/flagman/mongo_one/llms.txt Provides methods to remove single or multiple documents from a MongoDB collection based on specified query criteria. This allows for efficient data cleanup and management within the database. ```ruby # Delete a single document User.delete_one({ email: 'old@example.com' }) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.