antimattr/mongodb-migrations-bundle
Installation Add the bundle via Composer:
composer require antimattr/mongodb-migrations-bundle
Enable the bundle in config/bundles.php:
return [
// ...
Antimattr\MongoDBMigrationsBundle\MongoDBMigrationsBundle::class => ['all' => true],
];
Configuration
Update config/packages/antimattr_mongodb_migrations.yaml (or create it) with your MongoDB connection details:
antimattr_mongodb_migrations:
db: 'mongodb://localhost:27017'
db_name: 'your_database'
collection: 'migrations'
First Migration
Create a migration file in src/Migrations/ (or a custom directory):
php bin/console make:migration
Example migration (20240101000000_CreateUsersCollection.php):
<?php
namespace App\Migrations;
use Antimattr\MongoDBMigrationsBundle\Migration\Migration;
use Doctrine\MongoDB\Collection;
class CreateUsersCollection extends Migration
{
public function up(Collection $collection): void
{
$collection->createIndex(['email' => 1], ['unique' => true]);
}
public function down(Collection $collection): void
{
$collection->dropIndex('email_1');
}
}
Run Migrations Execute migrations:
php bin/console mongodb:migrate
Rollback if needed:
php bin/console mongodb:migrate:rollback
Verify
Check the migrations collection in MongoDB for recorded versions.
Use this bundle to:
up()/down() methods).updateOne()).Version Control
src/Migrations/).YYYYMMDDHHmmss_Description.php for chronological ordering.Atomic Changes
created_at field and index together.Rollback Safety
down() to reverse changes.Environment-Specific Migrations
%env%) in config to target dev/staging/prod.antimattr_mongodb_migrations:
db: '%env(MONGODB_URL)%'
Dependency Management
setOrder() in the bundle config:
antimattr_mongodb_migrations:
migrations_order: ['20240101000000_CreateUsers', '20240102000000_AddIndexes']
Doctrine ODM Integration If using Doctrine MongoDB ODM, sync migrations with entity changes:
// In up(): Add index for @Index annotation
$collection->createIndex(['slug' => 1], ['unique' => true]);
// In down(): Drop the index
$collection->dropIndex('slug_1');
Custom Migration Commands Extend the bundle’s command to add pre/post hooks:
// src/Command/CustomMigrateCommand.php
use Antimattr\MongoDBMigrationsBundle\Command\MigrateCommand;
class CustomMigrateCommand extends MigrateCommand
{
protected function execute(InputInterface $input, OutputInterface $output): int
{
$this->logPreMigration($output);
return parent::execute($input, $output);
}
}
Update services.yaml to override the command.
Parallel Migrations For large datasets, use batch processing in migrations:
public function up(Collection $collection): void
{
$bulk = [];
foreach ($this->getBatchData() as $data) {
$bulk[] = ['insertOne' => ['document' => $data]];
if (count($bulk) >= 100) {
$collection->bulkWrite($bulk);
$bulk = [];
}
}
if (!empty($bulk)) {
$collection->bulkWrite($bulk);
}
}
Event Listeners Trigger actions before/after migrations via Symfony events:
# config/services.yaml
services:
App\EventListener\MigrationListener:
tags:
- { name: kernel.event_listener, event: mongodb.migration.before, method: onMigrationStart }
Collection Existence
create() in up() if needed:
public function up(Collection $collection): void
{
if (!$collection->exists()) {
$this->manager->createCollection($collection->getName());
}
// Rest of the migration...
}
Index Naming Collisions
$collection->createIndex(['email' => 1], ['unique' => true, 'name' => 'email_1_' . time()]);
Transaction Limitations
Timezone Sensitivity
Schema Validation
Dry Runs Enable verbose output to preview changes:
php bin/console mongodb:migrate --verbose
Migration Logs
Check the migrations collection for executed versions:
db.migrations.find().sort({ executed_at: -1 }).limit(10);
Collection Dumps
Use mongodump to back up collections before risky migrations:
mongodump --db your_database --collection users --out /backup/
Custom Migration Classes
Extend Antimattr\MongoDBMigrationsBundle\Migration\Migration to add shared logic:
abstract class BaseMigration extends Migration
{
protected function log(string $message): void
{
$this->output->writeln('<comment>[' . get_class($this) . ']</comment> ' . $message);
}
}
Dynamic Config Load migration config from environment variables or files:
antimattr_mongodb_migrations:
db: '%env(resolve:MONGODB_URL)%'
db_name: '%kernel.project_dir%/config/mongodb/name.yaml'
Migration Tags
Tag migrations for conditional execution (e.g., dev-only):
// In migration class
public function getTags(): array
{
return ['dev'];
}
Filter in a custom command:
$migrations = $this->migrationFinder->findMigrations(['tags' => ['dev']]);
Post-Migration Hooks
Use Symfony’s kernel.terminate event to run post-migration tasks:
// src/EventListener/PostMigrationListener.php
public function onKernelTerminate(KernelEvents::TERMINATE, Event $event)
{
if ($event->getRequest()->attributes->get('migration_running')) {
$this->notifyTeam('Migrations completed');
}
}
Default Collection
The bundle defaults to a migrations collection. Change it via config:
antimattr_mongodb_migrations:
collection: 'schema_migrations'
Connection Switching Use multiple configs for different environments:
antimattr_mongodb_migrations:
default_connection: 'default'
connections:
default: { db: 'mongodb://localhost:27017', db_name: 'app' }
staging: { db: 'mongodb://staging:27017', db_name
How can I help you explore Laravel packages today?