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

doctrine/mongodb

Doctrine MongoDB library for PHP, providing an object-oriented API for working with MongoDB. Includes database and collection abstractions, query and command builders, and tools for common CRUD operations—ideal as a low-level MongoDB foundation for PHP apps.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup in Laravel

  1. Installation

    composer require doctrine/mongodb:^1.6.4
    

    (Note: This package is archived. For new projects, consider jenssegers/laravel-mongodb or the official mongodb/mongodb driver. Ensure PHP 7.4+ and MongoDB 4.0+ compatibility.)

  2. Configure MongoDB Connection Add a MongoDB connection in config/database.php:

    'connections' => [
        'mongodb' => [
            'driver' => 'mongodb',
            'host' => env('DB_MONGODB_HOST', '127.0.0.1'),
            'port' => env('DB_MONGODB_PORT', 27017),
            'database' => env('DB_MONGODB_DATABASE', 'laravel'),
            'username' => env('DB_MONGODB_USERNAME'),
            'password' => env('DB_MONGODB_PASSWORD'),
            'options' => [
                'connect' => env('DB_MONGODB_CONNECT', false), // Set to `false` in production
            ],
        ],
    ],
    
  3. First Query Use the MongoDBManager facade to interact with collections:

    use Doctrine\MongoDB\MongoDBManager;
    
    $manager = MongoDBManager::connection('mongodb');
    $collection = $manager->selectCollection('users');
    
    $user = $collection->findOne(['email' => 'test@example.com']);
    
  4. Eloquent Integration (Optional) For Eloquent-like syntax, use jenssegers/laravel-mongodb (recommended):

    composer require jenssegers/laravel-mongodb
    

Implementation Patterns

Common Workflows

  1. CRUD Operations

    // Insert
    $collection->insertOne(['name' => 'John', 'email' => 'john@example.com']);
    
    // Update with `replaceRoot` (fixed in 1.6.4)
    $collection->updateOne(
        ['email' => 'john@example.com'],
        ['$set' => ['name' => 'John Doe']]
    );
    
    // Delete
    $collection->deleteOne(['email' => 'john@example.com']);
    
  2. Aggregation Pipeline (Fixed replaceRoot Stage)

    $pipeline = [
        ['$match' => ['status' => 'active']],
        ['$replaceRoot' => ['newRoot' => ['$mergeObjects' => ['$$ROOT', { 'activeSince' => '$createdAt' }]]]], // Now works correctly
        ['$group' => ['_id' => '$department', 'count' => ['$sum' => 1]]],
    ];
    $results = $collection->aggregate($pipeline);
    
  3. Transactions (Multi-Document)

    $session = $manager->createSession();
    $session->startTransaction();
    
    try {
        $collection1->insertOne([...], ['session' => $session]);
        $collection2->insertOne([...], ['session' => $session]);
        $session->commitTransaction();
    } catch (\Exception $e) {
        $session->abortTransaction();
    }
    
  4. Index Management

    $collection->createIndex(['email' => 1], ['unique' => true]);
    

Integration Tips

  • Laravel Service Providers: Bind the MongoDBManager to the container:
    $this->app->singleton('mongodb', function ($app) {
        return MongoDBManager::connection('mongodb');
    });
    
  • Query Builder: Use Doctrine\MongoDB\Query\Query for complex queries:
    $query = new Query();
    $query->where('age')->gt(18);
    $results = $collection->find($query);
    
  • Hydration: Convert BSON to PHP objects with validation:
    $hydrator = new \Doctrine\MongoDB\Hydrator\ObjectHydrator();
    $user = $hydrator->hydrate($collection->findOne([...]), User::class);
    

Gotchas and Tips

Pitfalls

  1. Archived Package: Still not maintained. Prefer jenssegers/laravel-mongodb or the official driver.
  2. replaceRoot Stage: Fixed in 1.6.4, but test thoroughly if using aggregation pipelines with this stage.
  3. Type Safety: MongoDB’s schema-less nature conflicts with Doctrine’s hydration. Validate data before hydration.
  4. Connection Pooling: Set options['connect'] to false in production to avoid overhead.
  5. BSON Limits: Large documents (>16MB) may fail. Use GridFS for files.
  6. Transactions: Require MongoDB 4.0+. Test multi-document transactions carefully.

Debugging

  • Query Logging: Enable debug mode:
    $manager->getClient()->setLoggerLevel(\MongoDB\Driver\Logger::DEBUG);
    
  • BSON Errors: Inspect raw data with json_encode($document, JSON_PRETTY_PRINT).
  • Aggregation Issues: Validate pipeline stages (e.g., replaceRoot syntax).

Extension Points

  1. Custom Hydrators: Extend \Doctrine\MongoDB\Hydrator\HydratorInterface for custom mapping.
  2. Event Listeners: Attach hooks to MongoDBManager for pre/post-query logic.
  3. Query Middleware: Add global conditions via middleware:
    $manager->getClient()->executeQuery('admin.$cmd', ['ping' => 1]);
    
  4. Schema Validation: Implement MongoDB\BSON\Type\Type for custom BSON types.
  5. Aggregation Pipelines: Leverage fixed stages (e.g., replaceRoot) for complex transformations.
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity