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

Module Mongodb Laravel Package

codeception/module-mongodb

Codeception module for MongoDB that integrates MongoDB into your test suite: clean collections between tests, load fixtures, and assert against documents using Codeception helpers. Ideal for functional and acceptance testing of MongoDB-backed PHP apps.

View on GitHub
Deep Wiki
Context7

Getting Started

codeception/module-mongodb is the official Codeception module for MongoDB. The low star count is because it is a read-only split of Codeception's module monorepo, not because it is unused; treat it as a first-party integration.

Minimal setup for a Laravel project already using Codeception:

composer require --dev codeception/codeception codeception/module-mongodb
# plus whichever driver you need for the app surface:
composer require --dev codeception/module-laravel codeception/module-rest
vendor/bin/codecept bootstrap

Make sure PHP has ext-mongodb installed and that the Composer dependency mongodb/mongodb is present; the module talks through the modern MongoDB PHP library.

Enable the module in the relevant suite. Use parameters rather than hard-coded credentials:

# codeception.yml
params:
    - .env.testing
# tests/functional.suite.yml
actor: FunctionalTester
modules:
    enabled:
        - Laravel:
            environment_file: .env.testing
        - REST:
            depends: Laravel
        - MongoDb:
            dsn: '%MONGO_TEST_DSN%'       # e.g. mongodb://127.0.0.1:27017
            database: '%MONGO_TEST_DB%'   # e.g. app_test
            cleanup: true

First useful test: drive the app through its API and assert the persisted document directly:

final class OrderApiCest
{
    public function persistsOrder(FunctionalTester $I): void
    {
        $I->haveHttpHeader('Accept', 'application/json');
        $I->sendPost('/api/orders', ['sku' => 'SKU-1', 'qty' => 2]);
        $I->seeResponseCodeIs(201);

        $I->seeInCollection('orders', ['sku' => 'SKU-1', 'qty' => 2]);
        $I->seeNumRecords(1, 'orders', ['sku' => 'SKU-1']);
    }
}

Where to look first:

  1. The package README and src/Codeception/Module/MongoDb.php for the exact method signatures in the installed version.
  2. The Codeception MongoDB module documentation.
  3. A scratch test using grabFromCollection() and codecept_debug() before writing many assertions, because return shapes and matching semantics differ from what you may expect from Eloquent.

Implementation Patterns

Seed, act, assert. The module is strongest as a black-box assertion tool. Use haveInCollection() for setup, exercise the app through Laravel/REST, then use seeInCollection(), seeNumRecords(), grabFromCollection(), and grabCollectionCount() to verify persistence.

$userId = $I->haveInCollection('users', [
    'email' => '[email protected]',
    'active' => true,
]);

$I->sendPost("/api/users/{$userId}/orders", ['sku' => 'SKU-1']);
$I->seeResponseCodeIs(201);

$I->seeInCollection('orders', [
    'user_id' => $userId,
    'sku' => 'SKU-1',
]);

Use the inserted id, but mind its type. haveInCollection() returns the inserted id. Querying by _id afterwards may require an ObjectId rather than a string, depending on version and the _id type stored:

$id = $I->haveInCollection('orders', ['sku' => 'SKU-1']);

// If the stored _id is an ObjectId, compare with the correct BSON type.
$I->seeInCollection('orders', ['_id' => new MongoDB\BSON\ObjectId($id)]);

Verify this once in your environment; it is one of the most common first-run surprises.

Prefer domain helpers over raw collection calls in tests. Wrap seeding in a Codeception Helper or Cest base class so test bodies read in domain language and the collection names live in one place.

final class MongoFixtures extends \Codeception\Module
{
    public function haveActiveCustomer(string $email): string
    {
        return $this->getModule('MongoDb')->haveInCollection('users', [
            'email' => $email,
            'active' => true,
            'created_at' => new MongoDB\BSON\UTCDateTime(),
        ]);
    }
}

Enable that helper module alongside MongoDb and call $I->haveActiveCustomer(...).

Use useDatabase() deliberately for multi-tenant or per-process isolation. If your application switches MongoDB databases by tenant, switch the test module to the same database before asserting:

$I->useDatabase('tenant_acme_test');
$I->sendPost('/api/orders', ['sku' => 'SKU-1']);
$I->seeInCollection('orders', ['sku' => 'SKU-1']);

Because the module holds a current database internally, reset it in a helper's _after() hook or at the end of the test. Do not assume a later test is still on the default database.

For parallel or sharded runs, give each process its own database. cleanup: true is database-wide; two workers on the same database will delete each other's fixtures. Build the database name from an environment variable or worker id:

MongoDb:
    dsn: '%MONGO_TEST_DSN%'
    database: 'app_test_%TEST_WORKER_ID%'
    cleanup: true

Fixture strategy. The module supports a dump option, but for anything beyond trivial baseline data, programmatic seed methods or a PHP fixture file are usually easier to maintain and debug than a MongoDB shell dump. Use haveInCollection() inside suite _before() hooks or StepObjects for shared fixtures.

Laravel integration. If you want MongoDb assertions to see writes made by the Laravel application under test, point both the Laravel module's .env.testing MongoDB settings and the MongoDb module at the same test database. If you keep them separate, you must seed both stores explicitly. Remember that Laravel's RefreshDatabase, database transactions, and model factories do not manage MongoDB state.

Cleanup policy. In CI, keep cleanup: true. For read-only acceptance suites against a pre-seeded database, set it to false and own the lifecycle yourself. In all cases, assert the configured database name is a dedicated test database before enabling cleanup.

Gotchas and Tips

  • Never point dsn or database at a real environment. With cleanup: true, the module wipes the configured database between tests. This is destructive by design. Guard with .env.testing, a dedicated database name, and CI-only credentials.
  • Cleanup may drop collections, which also drops indexes. If your application depends on unique indexes, partial indexes, or TTL indexes, tests may pass or fail differently after cleanup because the index definitions are gone. Recreate indexes in a bootstrap hook or confirm the installed module's cleanup behavior before relying on them.
  • _id type mismatches are the most common assertion failure. A string id from haveInCollection() is not automatically the same as an ObjectId in the database. Use the correct BSON type when querying by _id, or match on a separate unique field such as email or sku.
  • Partial-document matching is not Eloquent-style matching. seeInCollection() builds a MongoDB query, so nested arrays, dates, decimals, and null values follow MongoDB equality semantics. For complex BSON values, grab the document and assert in PHP instead of relying on a nested seeInCollection().
  • Avoid empty criteria in negative assertions. dontSeeInCollection('orders', []) is effectively "no documents match anything," which is rarely what you mean and produces confusing results.
  • seeCollection() and dontSeeCollection() only check existence. An existing but empty collection passes seeCollection(). Use seeNumRecords(0, ...) or grabCollectionCount() when emptiness matters.
  • JS dump loading can depend on the legacy mongo shell. Many CI images and modern MongoDB installs no longer ship the old mongo binary, and the equivalent is mongosh. If your dump uses a .js fixture and seeding appears to do nothing, check the module's dump-loading implementation and the shell binary on PATH. Prefer PHP fixtures or haveInCollection() calls.
  • Don't assume dumps survive useDatabase(). If you load a dump and then switch databases, the fixture may only exist in the original database. Load fixtures after switching, or seed explicitly.
  • Laravel config caching can override your test DSN. Run php artisan config:clear in CI bootstrap or ensure bootstrap/cache/config.php is absent when .env.testing is expected to apply.
  • Database transactions do not cover MongoDB. Laravel's transaction helpers and RefreshDatabase are SQL-oriented. If your test writes through Eloquent/MySQL and MongoDB, you need separate cleanup plans for each store.
  • Module load order matters for HTTP drivers. REST needs a working depends configuration, and MongoDb is independent. Keep MongoDb last in the enabled list for readability; it does not need to initialize before the HTTP modules.
  • Debug with the database, not guesses. When an assertion fails, run the test with --debug, then add a temporary codecept_debug($I->grabFromCollection('collection', $criteria)); to inspect the actual document shape. Check collection names with grabCollectionNames() and counts with grabCollectionCount().
  • Extension point: subclass the module if you need the raw client. The MongoDB client/database handles are protected. For custom queries beyond the built-in actions, extend Codeception\Module\MongoDb in your _support directory and expose narrow helper methods rather than making tests talk to the driver directly.
  • Pin and upgrade consciously. This package follows the MongoDB PHP library and Codeception major versions. A Codeception major upgrade can change module configuration or actor behavior; run one suite against the new version before upgrading the whole project.
  • The low star count is not a risk signal by itself. The package is maintained as part of Codeception's official module set. Evaluate it by its release history against your Codeception and mongodb/mongodb versions, not by GitHub stars.
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.
takashato/laravel-vietqr
aitor24/laralang
kraenzle-ritter/entity-relations
dindigital/din-image
pomirleanu/image-colors
sawmainek/laravel-api-generator
delatbabel/jsonresponses
mouhamedfd/permissions-generator
eduplus/qr
laravel2580/idehelpers
delatbabel/viewpages
anavel/gettext
muhamadrezaar/highcharts
delatbabel/keylists
frankkessler/salesforce-laravel-oauth2-rest
anavel/foundation
wdmtech/enviricons
eii/laravel-captcha
muka/shape-reader
tdt/json