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

Laravel Mongodb Laravel Package

mongodb/laravel-mongodb

MongoDB integration for Laravel Eloquent and the Query Builder, extending the native Laravel API to work with MongoDB. Official mongodb/laravel-mongodb package (formerly jenssegers), compatible with Laravel 10.x.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Schema Flexibility vs. Relational Constraints: The package bridges Laravel’s Eloquent ORM with MongoDB’s document model, enabling schema flexibility (e.g., dynamic fields, nested documents) while retaining Laravel’s query builder syntax. This is ideal for projects requiring agile data modeling (e.g., user-generated content, IoT telemetry) but risks inconsistent data integrity if relational constraints (e.g., foreign keys, transactions) are critical.
  • Hybrid Workloads: Supports mixed relational/document queries (e.g., joins with $lookup), but performance degrades for complex hybrid operations due to MongoDB’s lack of native SQL-like joins. Key trade-off: Flexibility over ACID compliance.
  • Event-Driven Patterns: Leverages Laravel’s event system (e.g., ModelObserver) for MongoDB operations, enabling seamless integration with queues, notifications, and real-time updates.

Integration Feasibility

  • Laravel Compatibility: Officially supports Laravel 10–13.x with backward compatibility for older versions. Critical: Validate against your Laravel version to avoid deprecated method conflicts (e.g., DatabaseTransactionsManager changes in v5.6.0).
  • MongoDB Driver Dependency: Requires PHP MongoDB Driver v2.0+ (bundled with mongodb/mongodb). Risk: Driver version mismatches may break operations (e.g., transactions, aggregation pipelines).
  • Existing Codebase Impact:
    • Minimal Changes: Eloquent syntax remains identical (e.g., User::where('age', '>', 25)->get()), but indexing strategies must shift from SQL to MongoDB (e.g., compound indexes, text indexes).
    • Migration Path: Use php artisan migrate with custom MongoDB migrations (e.g., Schema::createCollection()) or leverage Laravel’s schema builder for hybrid setups.

Technical Risk

  • Data Modeling Pitfalls:
    • Denormalization: MongoDB favors embedded documents over joins. Risk: Over-denormalization leads to update anomalies (e.g., inconsistent nested data).
    • Id Handling: MongoDB uses _id (ObjectId), while Eloquent defaults to incremental IDs. Mitigation: Configure protected $primaryKey = '_id' and protected $keyType = 'string' in models.
  • Performance Anti-Patterns:
    • N+1 Queries: Eager loading (with()) works but may generate inefficient $lookup stages. Solution: Use load() or batch loading for related documents.
    • Aggregation Complexity: MongoDB’s aggregation framework lacks Laravel’s query builder optimizations. Risk: Poorly optimized pipelines cause server-side timeouts.
  • Transaction Limitations:
    • MongoDB transactions are multi-document but not multi-collection by default. Workaround: Use retry logic for failed transactions (e.g., MongoBatchRepository::retry()).
    • No Distributed Transactions: Cross-database transactions (e.g., SQL + MongoDB) require application-level coordination.

Key Questions

  1. Data Model Requirements:
    • Do you need strict relational integrity (e.g., foreign keys, cascading deletes), or is flexible schema a priority?
    • Are there high-frequency writes that could benefit from MongoDB’s atomic operators (e.g., $inc, $push)?
  2. Query Patterns:
    • Will your application rely heavily on complex joins, full-text search, or geospatial queries? If so, how will you optimize these in MongoDB?
    • Are there legacy SQL queries that must be migrated to MongoDB’s aggregation framework?
  3. Operational Constraints:
    • What is your MongoDB deployment model (self-hosted, Atlas, etc.)? Atlas offers managed backups and auto-scaling, which may reduce operational overhead.
    • Do you have budget for MongoDB Atlas or will you self-manage clusters (increasing DevOps complexity)?
  4. Team Skills:
    • Does your team have experience with MongoDB’s data modeling (e.g., embedding vs. referencing) and aggregation pipelines?
    • Are developers familiar with Laravel’s Eloquent or will training be required for MongoDB-specific features (e.g., $out, $facet)?

Integration Approach

Stack Fit

  • Laravel Ecosystem: Seamless integration with:
    • Eloquent: Replace Illuminate\Database\Eloquent\Model with Jenssegers\Mongodb\Eloquent\Model.
    • Query Builder: Use MongoDB\Laravel\Eloquent\Builder for MongoDB-specific queries (e.g., $text, $geoNear).
    • Migrations: Extend Illuminate\Database\Migrations\Migrator with MongoDB support (e.g., Schema::createCollection()).
    • Scout: Replace SQL-based search with MongoDB’s text indexes or Atlas Search.
    • Queues/Jobs: Works with Laravel’s queue system; payloads are serialized to BSON.
  • Third-Party Packages:
    • Laravel Cashier: Requires customization for MongoDB (e.g., storing subscriptions in a separate collection).
    • Laravel Nova: Limited support; may need custom resources for MongoDB models.
    • Laravel Horizon: Compatible for queue monitoring, but job payloads must handle BSON serialization.
  • Testing:
    • PHPUnit: Use MongoDB\Laravel\Testing\CreatesCollections for test fixtures.
    • Pest: Supports MongoDB models via create() and factory().

Migration Path

  1. Assessment Phase:
    • Audit existing SQL queries for MongoDB compatibility (e.g., replace JOIN with $lookup, GROUP BY with $group).
    • Identify critical relational constraints (e.g., foreign keys) that may require denormalization or application-level enforcement.
  2. Pilot Migration:
    • Start with non-critical collections (e.g., logs, analytics) to test performance and query patterns.
    • Use dual-writes (SQL + MongoDB) during transition for data consistency.
  3. Schema Redesign:
    • Replace normalized tables with embedded documents where appropriate (e.g., user profiles with addresses nested under user).
    • Design indexes for common query patterns (e.g., { email: 1 }, { created_at: -1, status: 1 }).
  4. Application Layer Changes:
    • Update Eloquent models to extend Jenssegers\Mongodb\Eloquent\Model.
    • Replace raw SQL queries with MongoDB’s aggregation framework or Eloquent builders.
    • Configure MongoDB connections in config/database.php:
      'connections' => [
          'mongodb' => [
              'driver' => 'mongodb',
              'host' => env('DB_HOST', '127.0.0.1'),
              'port' => env('DB_PORT', 27017),
              'database' => env('DB_DATABASE', 'laravel'),
              'username' => env('DB_USERNAME'),
              'password' => env('DB_PASSWORD'),
              'options' => [
                  'connect' => true,
              ],
          ],
      ],
      
  5. Data Migration:
    • Use Laravel’s migration system or custom scripts to export SQL data to MongoDB.
    • Example: Convert a users table to a MongoDB collection with embedded posts:
      // SQL: users table with posts in a separate table
      // MongoDB: users collection with posts embedded
      $users = User::all()->each(function ($user) {
          $user->posts = Post::where('user_id', $user->id)->get();
          $user->save(); // Uses MongoDB's $push for nested documents
      });
      

Compatibility

  • Laravel Features:
    Feature MongoDB Support Notes
    Eloquent Relationships Yes (hasOne, hasMany, belongsTo) Uses $lookup under the hood.
    Soft Deletes Yes (via SoftDeletes trait) Deprecated in v5.5.0; use $set.
    Scopes Yes Custom scopes can use MongoDB operators.
    Accessors/Mutators Yes Works as in SQL Eloquent.
    Events Yes created, updated, etc.
    Transactions Partial (multi-doc, no cross-collection) Use MongoBatchRepository.
    Caching Yes (via cache() method) Uses Redis or file cache.
    File Storage Yes (via Storage facade) Works with S3, local, etc.
  • MongoDB-Specific Features:
    • Aggregation Pipelines: Access via Model::aggregate() or raw `$collection->
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