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**:
   ```bash
   composer require mongodb/laravel-mongodb

Add to config/app.php under providers:

MongoDB\Laravel\MongoDBServiceProvider::class,
  1. Configuration: Publish the config file:

    php artisan vendor:publish --provider="MongoDB\Laravel\MongoDBServiceProvider"
    

    Update .env with your MongoDB connection string:

    MONGODB_CONNECTION=default
    MONGODB_DATABASE=your_database
    MONGODB_URI=mongodb://username:password@host:port/database
    
  2. First Model: Extend MongoDB\Eloquent\Model in app/Models:

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

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

Key First Use Cases

  • CRUD Operations: Use create(), find(), update(), delete() just like Eloquent.
  • Aggregation: Leverage MongoDB’s native aggregation pipeline:
    $result = User::aggregate([
        ['$match' => ['age' => ['$gt' => 18]]],
        ['$group' => ['_id' => '$country', 'count' => ['$sum' => 1]]]
    ]);
    
  • Index Management:
    php artisan mongodb:create-index users email_text --unique
    

Implementation Patterns

Core Workflows

1. Model Design

  • Schema Flexibility: Use $casts for automatic type conversion (e.g., DateTime, Array):
    protected $casts = [
        'created_at' => 'date',
        'metadata' => 'array',
    ];
    
  • Embedded Documents: Define nested models with $embedded:
    class Profile extends Model
    {
        protected $embedded = true;
    }
    
    class User extends Model
    {
        public function profile()
        {
            return $this->embedsOne(Profile::class);
        }
    }
    

2. Query Building

  • Hybrid Queries: Combine Eloquent and MongoDB query builders:
    $query = User::query()
        ->where('status', 'active')
        ->whereIn('role', ['admin', 'editor'])
        ->orderBy('name', 'asc')
        ->limit(10);
    
  • Text Search:
    $results = User::textSearch('email', 'john')->get();
    
    Ensure a text index exists:
    php artisan mongodb:create-index users email_text --type text
    

3. Relationships

  • One-to-Many:
    class Post extends Model
    {
        public function user()
        {
            return $this->belongsTo(User::class);
        }
    }
    
  • Many-to-Many:
    class Role extends Model
    {
        public function users()
        {
            return $this->belongsToMany(User::class);
        }
    }
    
  • Polymorphic:
    class Comment extends Model
    {
        public function commentable()
        {
            return $this->morphTo();
        }
    }
    

4. Transactions

  • Use DB::transaction() for multi-document operations:
    DB::transaction(function () {
        User::create(['name' => 'John']);
        Profile::create(['user_id' => $user->id, 'bio' => 'Developer']);
    });
    

5. Events & Observers

  • Register observers in app/Providers/EventServiceProvider:
    protected $observers = [
        User::class => UserObserver::class,
    ];
    
  • Example observer:
    class UserObserver
    {
        public function saving(User $user)
        {
            if (empty($user->email)) {
                $user->email = $user->name . '@example.com';
            }
        }
    }
    

Integration Tips

Laravel Ecosystem

  • Scout: Use MongoDB for full-text search:
    composer require mongodb/laravel-scout
    
    Configure in config/scout.php:
    'driver' => 'mongodb',
    
  • Queues: Store jobs in MongoDB:
    QUEUE_CONNECTION=mongodb
    
  • Caching: Use MongoDB for session storage:
    SESSION_DRIVER=mongodb
    

Performance

  • Pagination: Use cursor-based pagination for large datasets:
    $users = User::orderBy('created_at')->paginate(20);
    
  • Batch Operations: Use chunk() for large updates:
    User::where('status', 'inactive')->chunk(100, function ($users) {
        foreach ($users as $user) {
            $user->update(['status' => 'active']);
        }
    });
    

Testing

  • Use MongoDB\Database\Client for in-memory testing:
    use MongoDB\Database\Client;
    
    $client = new Client('mongodb://localhost:27017', [
        'connect' => false,
        'directConnection' => true,
    ]);
    
  • Mock queries with MongoDB\Laravel\Testing\CreatesCollections:
    use MongoDB\Laravel\Testing\CreatesCollections;
    
    class UserTest extends TestCase
    {
        use CreatesCollections;
    
        public function test_user_creation()
        {
            $user = User::create(['name' => 'Test']);
            $this->assertDatabaseHas('users', ['name' => 'Test']);
        }
    }
    

Gotchas and Tips

Common Pitfalls

  1. _id vs id:

    • MongoDB uses _id by default, but the package aliases it to id for Eloquent compatibility.
    • Fix: Use $primaryKey = '_id' in your model if you prefer _id explicitly.
  2. Soft Deletes:

    • The SoftDeletes trait is deprecated. Use deleted_at with custom queries:
      User::whereNull('deleted_at')->get();
      
  3. Hybrid Queries:

    • Not all SQL queries translate to MongoDB. Avoid complex joins; use $lookup in aggregation instead:
      User::aggregate([
          ['$lookup' => [
              'from' => 'profiles',
              'localField' => '_id',
              'foreignField' => 'user_id',
              'as' => 'profile'
          ]]
      ]);
      
  4. Transactions:

    • MongoDB transactions require retry logic due to network issues. Use DB::transaction() with a retry wrapper:
      $attempts = 3;
      while ($attempts--) {
          try {
              DB::transaction(...);
              break;
          } catch (Exception $e) {
              if ($attempts === 0) throw $e;
              sleep(1);
          }
      }
      
  5. Schema Validation:

    • MongoDB does not enforce schema validation by default. Use $schema in your model:
      protected $schema = [
          'bsonType' => 'object',
          'required' => ['name', 'email'],
          'properties' => [
              'name' => ['bsonType' => 'string'],
              'email' => ['bsonType' => 'string', 'pattern' => '^.+@.+$']
          ]
      ];
      
    • Apply validation via:
      php artisan mongodb:validate-schema users
      

Debugging Tips

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

    MONGODB_DEBUG=true
    

    Logs will show executed queries in storage/logs/laravel.log.

  2. Explain Plans: Use explain() to analyze query performance:

    $explanation = User::where('age', '>', 18)->explain();
    dd($explanation);
    
  3. Connection Issues:

    • Ensure your MongoDB URI includes authentication and SSL if needed:
      MONGODB_URI=mongodb+srv://user:pass@cluster.mongodb.net/db?retryWrites=true&w=majority&ssl=true
      
    • For local development, use mongodb://localhost:27017.
  4. Index Optimization:

    • Use php artisan mongodb:show-indexes users to inspect indexes.
    • Drop unused indexes:
      php artisan mongodb:drop-index users email_text
      

Extension Points

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.
codraw/framework-extra-bundle
codraw/messenger
codraw/security
codraw/mailer
codraw/contracts
codraw/profiling
codraw/dependency-injection
codraw/tester
codraw/core
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony