Weave 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 Odm Laravel Package

doctrine/mongodb-odm

Doctrine MongoDB ODM is a PHP object-document mapper for MongoDB that lets you persist and query PHP objects as documents. It offers annotation, XML, and PHP mapping, repositories, a query builder, events, and integration with the Doctrine ecosystem for building flexible, document-based applications...

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup in Laravel

  1. Installation

    composer require doctrine/mongodb-odm
    composer require mongodb/mongodb
    
  2. Configure MongoDB Connection Add to 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,
            ],
        ],
    ],
    
  3. Define a Document Model

    use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;
    
    #[ODM\Document(collection: "users")]
    class User
    {
        #[ODM\Id]
        private ?string $id = null;
    
        #[ODM\Field(type: "string")]
        private string $name;
    
        // Getters/Setters...
    }
    
  4. Register ODM Service Provider In config/app.php:

    'providers' => [
        Doctrine\ODM\MongoDB\MongoDBServiceProvider::class,
    ],
    
  5. First Query

    use Doctrine\ODM\MongoDB\DocumentManager;
    
    $dm = app(DocumentManager::class);
    $user = $dm->find(User::class, 'some-id');
    

Implementation Patterns

Core Workflows

1. CRUD Operations

// Create
$user = new User();
$user->setName('John Doe');
$dm->persist($user);
$dm->flush();

// Read
$user = $dm->find(User::class, $user->getId());

// Update
$user->setName('Updated Name');
$dm->flush();

// Delete
$dm->remove($user);
$dm->flush();

2. Querying with QueryBuilder

$queryBuilder = $dm->createQueryBuilder(User::class)
    ->field('name')->equals('John Doe')
    ->field('age')->gt(18)
    ->sort('name', 'ASC')
    ->limit(10);

$users = $queryBuilder->getQuery()->execute();

3. Embedded Documents

#[ODM\EmbeddedDocument]
class Address
{
    #[ODM\Field(type: "string")]
    private string $street;
    // ...
}

#[ODM\Document]
class User
{
    #[ODM\EmbedOne(targetDocument: Address::class)]
    private ?Address $address = null;
}

4. References (Relationships)

#[ODM\Document]
class Post
{
    #[ODM\ReferenceOne(targetDocument: User::class)]
    private ?User $author = null;
}

5. Aggregation Pipeline

$pipeline = [
    ['$match' => ['age' => ['$gt' => 18]]],
    ['$group' => ['_id' => '$name', 'count' => ['$sum' => 1]]],
];

$results = $dm->createAggregationBuilder(User::class)
    ->pipeline($pipeline)
    ->getQuery()
    ->execute();

Integration with Laravel Ecosystem

1. Eloquent-like Facade

Create a facade for cleaner syntax:

// app/Facades/MongoDB.php
namespace App\Facades;

use Illuminate\Support\Facades\Facade;

class MongoDB extends Facade
{
    protected static function getFacadeAccessor() { return 'mongodb'; }
}

Register in AppServiceProvider:

public function register()
{
    $this->app->singleton('mongodb', function () {
        return app(DocumentManager::class);
    });
}

Usage:

$user = MongoDB::find(User::class, 'id');

2. Migrations

Use doctrine/mongodb-odm-module for schema migrations:

composer require doctrine/mongodb-odm-module
php artisan doctrine:mongo:schema:update --complete

3. Events & Observers

use Doctrine\ODM\MongoDB\Events;

$dm->getEventManager()->addEventListener(
    Events::postPersist,
    function ($event) {
        // Post-save logic
    }
);

4. Custom Types

Extend Type for custom field types:

use Doctrine\ODM\MongoDB\Types\Type;

class CustomType extends Type
{
    public function convertToPHPValue($value)
    {
        return json_decode($value, true);
    }

    public function convertToDatabaseValue($value)
    {
        return json_encode($value);
    }
}

Register in config/doctrine-mongodb-odm.php:

'types' => [
    'custom' => 'App\\Types\\CustomType',
],

Gotchas and Tips

Common Pitfalls

  1. Lazy Loading Issues

    • Enable native lazy objects for PHP 8.4+:
      'use_native_lazy_objects' => true,
      
    • Avoid circular references in embedded documents.
  2. QueryBuilder Caching

    • Clear the metadata cache after schema changes:
      php artisan doctrine:mongo:cache:clear-metadata
      
  3. Case Sensitivity in Field Names

    • MongoDB field names are case-sensitive. Use consistent naming conventions.
  4. Transactions

    • MongoDB does not support multi-document transactions by default. Use retry logic for critical operations.
  5. Index Management

    • Create indexes explicitly for performance:
      #[ODM\Index(name: "name_idx", fields: ["name" => "text"])]
      

Debugging Tips

  1. Enable Query Logging

    $dm->getConfiguration()->setSQLLogger(new \Doctrine\ODM\MongoDB\Logging\EchoSQLLogger());
    
  2. Check Hydration

    • Use useNativeLazyObjects: true to avoid proxy-related issues.
  3. Schema Validation

    • Validate your schema with:
      php artisan doctrine:mongo:schema:validate
      

Performance Optimization

  1. Projection Queries

    $queryBuilder->fields(['name' => true, 'email' => true]);
    
  2. Batch Operations

    $dm->createQueryBuilder(User::class)
        ->field('status')->equals('inactive')
        ->getQuery()
        ->execute(['delete' => true]);
    
  3. Index Utilization

    • Use explain() to analyze query performance:
      $queryBuilder->getQuery()->explain();
      

Extension Points

  1. Custom Hydrators

    use Doctrine\ODM\MongoDB\Hydrator\HydratorInterface;
    
    class CustomHydrator implements HydratorInterface
    {
        public function hydrate($document, $data)
        {
            // Custom logic
        }
    }
    
  2. Event Subscribers

    use Doctrine\ODM\MongoDB\Event\LifecycleEventArgs;
    
    $dm->getEventManager()->addEventSubscriber(new class {
        public function postLoad(LifecycleEventArgs $args)
        {
            // Post-load logic
        }
    });
    
  3. Custom Repository

    use Doctrine\ODM\MongoDB\Repository\DocumentRepository;
    
    class UserRepository extends DocumentRepository
    {
        public function findByName($name)
        {
            return $this->createQueryBuilder()
                ->field('name')->equals($name)
                ->getQuery()
                ->execute();
        }
    }
    

    Register in your document:

    #[ODM\Repository(class: UserRepository::class)]
    class User { ... }
    

Configuration Quirks

  1. Proxy Directory

    • Avoid setting proxy_dir manually; use the default (/runtime/Proxy).
  2. Connection Pooling

    • Configure in config/doctrine-mongodb-odm.php:
      'connection' => [
          'server' => [
              'type' => 'mongodb',
              'host' => 'localhost',
              'port' => 27017,
              'options' => [
                  'connect' => true,
                  'pool' => [
                      'min_size' => 1,
                      'max_size' => 10,
                  ],
              ],
          ],
      ],
      
  3. Read Preference

    • Configure
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.
dbravoan/dbcms-admin-theme-dbcms
dbravoan/dbcms-theme-db-cyber
dbravoan/dbcms-blocks-basic
dbravoan/dbcms-module-content-audit
dbravoan/dbcms-module-ai-assistant
paygate-to/paygate-php
padosoft/askmydocs-connector-base
defstudio/supercharged-carbon
bernskioldmedia/laravel-matomo
bernskioldmedia/laravel-harvest
bernskiold/laravel-data-scrubber
bernskiold/laravel-currency-converter
bernskiold/laravel-campaign-monitor
bernskioldmedia/laravel-autotranslate
siberfx/telegram-bot
roy-sandip/laravel-view-extended
gregsphotography/site-builder-core
roy-sandip/laravel-view
anodyne/blade-fluentui-icons
webx-ui/module-catalog-collections