Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Mongodb Laravel Package

jenssegers/mongodb

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require mongodb/laravel-mongodb
    

    Add the service provider to config/app.php:

    'providers' => [
        // ...
        MongoDB\Laravel\MongoDBServiceProvider::class,
    ],
    
  2. Configure .env:

    DB_CONNECTION=mongodb
    DB_HOST=127.0.0.1
    DB_PORT=27017
    DB_DATABASE=your_db_name
    
  3. First Model:

    use MongoDB\Eloquent\Model;
    
    class User extends Model
    {
        protected $connection = 'mongodb';
        protected $collection = 'users';
        protected $fillable = ['name', 'email'];
    }
    
  4. First Query:

    $users = User::where('email', 'user@example.com')->get();
    

Where to Look First

  • Official Docs: MongoDB Laravel Guide
  • Migration Guide: php artisan vendor:publish --provider="MongoDB\Laravel\MongoDBServiceProvider" --tag=migrations
  • Query Builder: Mimics Eloquent’s syntax but works with MongoDB’s schema.

Implementation Patterns

Core Workflows

  1. Model Definitions:

    • Use protected $collection to specify the MongoDB collection.
    • Leverage protected $fillable/$guarded for mass assignment (same as Eloquent).
    • Example:
      class Product extends Model
      {
          protected $collection = 'products';
          protected $fillable = ['name', 'price', 'tags'];
      }
      
  2. Querying:

    • Basic Queries:
      Product::where('price', '<', 100)->get();
      
    • Aggregation:
      Product::aggregate([
          ['$match' => ['price' => ['$gt' => 50]]],
          ['$group' => ['_id' => '$category', 'avg' => ['$avg' => '$price']]]
      ])->toArray();
      
    • Text Search:
      Product::where('name', 'text', 'laptop')->get();
      
  3. Relationships:

    • One-to-Many:
      class Order extends Model
      {
          public function items()
          {
              return $this->hasMany(OrderItem::class);
          }
      }
      
    • Embedded Documents:
      class User extends Model
      {
          protected $embeds = ['address'];
          protected $embedsOne = ['profile'];
      }
      
  4. Events & Observers:

    • Use observables() and dispatchesEvents() (same as Eloquent).
    • Example:
      class User extends Model
      {
          public static function boot()
          {
              parent::boot();
              static::created(function ($user) {
                  Log::info("New user created: {$user->email}");
              });
          }
      }
      
  5. Transactions:

    • Use DB::transaction() for multi-document operations:
      DB::transaction(function () {
          User::create(['name' => 'John']);
          Product::create(['name' => 'Laptop']);
      });
      

Integration Tips

  • Hybrid Apps: Combine MongoDB models with SQL models in the same app.
    class HybridModel extends Model
    {
        protected $connection = 'mysql'; // Defaults to SQL
    }
    
  • Laravel Scout: Use MongoDB for full-text search:
    class Product extends Model
    {
        public function toSearchableArray()
        {
            return ['name' => $this->name, 'description' => $this->description];
        }
    }
    
  • API Resources: Transform MongoDB models into JSON:
    php artisan make:resource ProductResource
    

Gotchas and Tips

Pitfalls

  1. Schema Differences:

    • MongoDB lacks strict schemas. Ensure data consistency with validation (e.g., Laravel’s FormRequest or custom validation rules).
    • Example:
      use Illuminate\Support\Facades\Validator;
      
      $validator = Validator::make($data, [
          'email' => 'required|email',
          'age' => 'integer|min:18',
      ]);
      
  2. Indexing:

    • Create indexes manually for performance:
      Schema::connection('mongodb')->create('users', function (Blueprint $collection) {
          $collection->index('email', 'unique');
          $collection->index('name');
      });
      
    • Avoid missing indexes on frequently queried fields (e.g., email, created_at).
  3. Relationships:

    • Embedded relationships ($embeds) require explicit handling:
      $user = User::find(1);
      $user->address->push(['city' => 'New York']); // Update embedded doc
      $user->save();
      
    • Reference relationships ($references) behave like SQL joins but may impact performance.
  4. Pagination:

    • Use cursor() for large datasets to avoid memory issues:
      $cursor = Product::where('price', '>', 100)->cursor();
      foreach ($cursor as $product) {
          // Process one item at a time
      }
      
  5. Atomic Operators:

    • MongoDB’s $inc, $push, etc., require explicit syntax:
      User::where('email', 'user@example.com')
          ->update(['$inc' => ['age' => 1]]); // Increment age by 1
      

Debugging

  1. Query Logging: Enable debug mode in .env:

    MONGO_DEBUG=true
    

    Logs will appear in storage/logs/laravel.log.

  2. Raw Queries: Use toMongo() to inspect raw queries:

    $query = User::where('name', 'John')->getQuery();
    dd($query->toMongo());
    
  3. Connection Issues:

    • Verify .env credentials and MongoDB server status.
    • Test connectivity with:
      DB::connection('mongodb')->getMongoClient()->selectDatabase('your_db')->command(['ping' => 1]);
      

Extension Points

  1. Custom Operators: Extend the query builder with custom MongoDB operators:

    use MongoDB\Eloquent\Builder;
    
    Builder::macro('customOperator', function ($field, $operator) {
        return $this->where($field, $operator);
    });
    

    Usage:

    User::customOperator('age', ['$gt' => 25])->get();
    
  2. Model Events: Override boot() for custom logic:

    class User extends Model
    {
        public static function boot()
        {
            parent::boot();
            static::retrieved(function ($user) {
                if (!$user->profile) {
                    $user->profile = new stdClass(); // Initialize embedded doc
                }
            });
        }
    }
    
  3. Query Scopes: Add reusable query logic:

    class User extends Model
    {
        public function scopeActive($query)
        {
            return $query->where('status', 'active');
        }
    }
    

    Usage:

    User::active()->get();
    
  4. Middleware: Use Laravel middleware to modify MongoDB queries:

    class LogMongoQueries
    {
        public function handle($request, Closure $next)
        {
            if (app()->bound('mongodb')) {
                \Log::info('MongoDB query executed');
            }
            return $next($request);
        }
    }
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope