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: MongoDB’s document model aligns well with Laravel’s Eloquent API, enabling flexible schema design (e.g., nested arrays, dynamic fields) without rigid migrations. Ideal for projects requiring agility in data structure evolution (e.g., SaaS platforms, analytics dashboards).
  • Query Abstraction: The package extends Laravel’s Query Builder, preserving familiarity while leveraging MongoDB’s rich query language (e.g., aggregation pipelines, geospatial queries). Useful for complex analytics or real-time data processing.
  • Hybrid Workloads: Supports mixed relational/document use cases (e.g., joins via $lookup in aggregation pipelines) but may introduce performance trade-offs for heavily relational data.
  • Laravel Ecosystem: Seamless integration with Laravel’s service container, caching (Redis/Memcached), and task scheduling (e.g., queues). Complements Laravel’s built-in tools like Scout for search or Horizon for jobs.

Integration Feasibility

  • Minimal Boilerplate: Replaces extends Model with extends Document, with identical method signatures (e.g., find(), create()). Migration effort is low for teams already using Eloquent.
  • Database Agnostic Code: Existing Laravel applications can abstract database access behind repositories/interfaces, easing future swaps (e.g., SQL → NoSQL).
  • Tooling Support: Works with Laravel Forge, Envoyer, and Homestead for deployment. Compatible with Laravel’s telescope for query monitoring and horizon for job processing.

Technical Risk

  • Performance Overheads:
    • NoSQL vs. SQL: MongoDB lacks native joins, requiring application-level denormalization or $lookup pipelines, which can impact read performance.
    • Indexing: Manual index management is required (e.g., text indexes, TTL indexes). Missing indexes may lead to collection scans.
    • Transactions: Multi-document ACID transactions are supported but may introduce latency compared to SQL.
  • Schema Evolution: Lack of migrations for schema changes (e.g., adding fields) requires manual $set operations or third-party tools (e.g., laravel-mongodb-schema).
  • Driver Dependencies: Requires the MongoDB PHP Driver (v2.0+), which must be installed system-wide (pecl install mongodb).
  • Legacy Quirks:
    • Soft deletes are deprecated in favor of MongoDB’s native deleted_at field.
    • Hybrid queries (SQL + NoSQL) may fail without explicit handling.

Key Questions

  1. Data Model Requirements:
    • Is the data highly relational (e.g., complex joins), or is a document model more natural?
    • Are there requirements for hierarchical/nested data (e.g., JSON arrays, subdocuments)?
  2. Performance SLAs:
    • Are there strict latency requirements for read/write operations?
    • Will the application scale to millions of documents per collection?
  3. Team Expertise:
    • Does the team have experience with MongoDB’s query language (e.g., aggregation pipelines)?
    • Is there familiarity with NoSQL design patterns (e.g., denormalization, sharding)?
  4. Operational Constraints:
    • Are there compliance requirements (e.g., GDPR) that necessitate specific data modeling (e.g., TTL indexes for retention)?
    • Is the team comfortable managing indexes, backups, and schema changes manually?
  5. Migration Path:
    • What is the current database schema, and how will it map to MongoDB collections?
    • Are there existing Laravel models that need to be refactored to Document?
  6. Tooling Compatibility:
    • Does the team use Laravel Debugbar, Telescope, or other tools that rely on SQL introspection?
    • Are there third-party packages (e.g., Laravel Scout) that need MongoDB-specific configurations?

Integration Approach

Stack Fit

  • Laravel Versions: Officially supports Laravel 10.x–13.x. For older versions, use the 3.x branch.
  • PHP Requirements: Requires PHP 8.1+ (Laravel 10+) or PHP 8.2+ (Laravel 11+). Tested up to PHP 8.5.
  • MongoDB Driver: Mandates MongoDB PHP Driver v2.0+, which must be installed via PECL.
  • Dependencies:
    • Extends Laravel’s Eloquent and Query Builder, so no conflicts with core Laravel packages.
    • Compatible with Laravel’s caching (Redis, Memcached), queues (database/Redis), and sessions (MongoDB session driver included).

Migration Path

  1. Assessment Phase:
    • Audit existing Eloquent models for relational dependencies (e.g., hasMany, belongsTo). Identify candidates for denormalization or $lookup pipelines.
    • Profile current database queries to anticipate performance changes (e.g., joins → aggregation pipelines).
  2. Setup:
    • Install the package:
      composer require mongodb/laravel-mongodb
      
    • Configure .env:
      DB_CONNECTION=mongodb
      DB_HOST=127.0.0.1
      DB_PORT=27017
      DB_DATABASE=your_db
      DB_USERNAME=your_user
      DB_PASSWORD=your_password
      
    • Publish config (optional):
      php artisan vendor:publish --provider="MongoDB\Laravel\MongoDBServiceProvider" --tag="config"
      
  3. Model Migration:
    • Replace use Illuminate\Database\Eloquent\Model; with use MongoDB\Laravel\Eloquent\Model;.
    • Extend Document instead of Model:
      use MongoDB\Laravel\Eloquent\Model as Document;
      
      class User extends Document { ... }
      
    • Update relationships to use MongoDB-specific syntax where needed (e.g., $lookup for joins).
  4. Query Adaptation:
    • Replace SQL-specific features (e.g., DB::raw('JSON_EXTRACT')) with MongoDB equivalents (e.g., $elemMatch, $arrayElemAt).
    • Update migrations to use MongoDB’s schema validation or manual $set operations for schema changes.
  5. Testing:
    • Test aggregation pipelines, geospatial queries, and transactions.
    • Validate performance under load (e.g., using Laravel Dusk or PHPUnit).

Compatibility

  • Laravel Features:
    • Eloquent: Full support for relationships (hasOne, belongsToMany), accessors/mutators, and events.
    • Query Builder: Supports where(), orderBy(), groupBy(), and raw MongoDB queries via $query->raw(['$match' => [...]]).
    • Migrations: Limited support; schema changes require manual operations or third-party tools.
    • Scout: Compatible with MongoDB for full-text search.
    • Caching: Uses Redis/Memcached by default; MongoDB session driver available.
  • Third-Party Packages:
    • Laravel Nova: Limited support; customizations may be needed for MongoDB-specific features.
    • Laravel Echo/Pusher: No direct impact; uses Redis by default.
    • Laravel Sanctum/Passport: Works as-is; token storage can use MongoDB collections.

Sequencing

  1. Phase 1: Non-Critical Models
    • Start with non-critical models (e.g., logs, analytics) to validate the migration process.
    • Use feature flags to toggle between SQL and MongoDB data sources.
  2. Phase 2: Core Domain Models
    • Migrate primary domain models (e.g., User, Product) with careful attention to relationships.
    • Implement $lookup pipelines for complex joins or denormalize data where feasible.
  3. Phase 3: Full Cutover
    • Replace remaining SQL queries with MongoDB equivalents.
    • Update CI/CD pipelines to include MongoDB-specific tests (e.g., index validation).
  4. Phase 4: Optimization
    • Add indexes based on query patterns.
    • Implement read replicas for scaling reads.
    • Fine-tune aggregation pipelines for performance.

Operational Impact

Maintenance

  • Schema Management:
    • Pros: No migrations for schema changes; fields can be added dynamically.
    • Cons: Manual management of indexes, validation rules, and data consistency. Use tools like:
      • MongoDB Compass for visualization.
      • laravel-mongodb-schema for validation rules.
  • Backups:
    • MongoDB requires separate backup strategies (e.g., mongodump, Atlas backups). Integrate with Laravel’s backup system via custom commands.
  • Monitoring:
    • Use MongoDB Atlas or Ops Manager for performance metrics (e.g., query profiling, index usage).
    • Integrate with Laravel’s monitoring tools (e.g., Telescope) via custom listeners for MongoDB events.

Support

  • Troubleshooting:
    • Debugging complex queries may require MongoDB-specific tools (e.g., explain() plans).
    • Log aggregation pipeline execution times and index usage.
  • Community:

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.
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
anil/file-picker
broqit/fields-ai