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

Yii2 Mongodb Laravel Package

yiisoft/yii2-mongodb

The official Yii2 MongoDB extension integrates MongoDB with the Yii framework, providing Connection, Query, Collection, and ActiveRecord components. It enables Yii2 applications to use MongoDB collections through familiar Yii APIs, including query building, data access, and model persistence.

Deep Wiki
Context7

Getting Started

Install via Composer:

composer require yiisoft/yii2-mongodb

The package depends on the mongodb PHP extension (the modern driver from pecl install mongodb), not the deprecated legacy mongo extension. Verify with php -m | grep mongodb before going further — this is the single most common installation failure.

Register the connection as an application component in config/web.php (or console.php):

'components' => [
    'mongodb' => [
        'class' => 'yii\mongodb\Connection',
        'dsn' => 'mongodb://localhost:27017/myapp',
    ],
],

The DSN must include the database name (the path segment after the host/port). If you omit it, calls that implicitly resolve a collection will throw because there is no default database.

First use case — an ActiveRecord model. Start here because it's what most day-to-day work looks like:

use yii\mongodb\ActiveRecord;

class User extends ActiveRecord
{
    public static function collectionName(): string
    {
        return 'users';
    }

    public function attributes(): array
    {
        return ['_id', 'name', 'email', 'created_at'];
    }
}

Then read and write like you would with a SQL AR:

$user = new User(['name' => 'Sam', 'email' => '[email protected]']);
$user->save();

$recent = User::find()->where(['name' => 'Sam'])->orderBy(['created_at' => SORT_DESC])->limit(10)->all();

Where to look first in the source tree: Connection.php, Collection.php, Command.php, ActiveQuery.php, ActiveRecord.php. If you understand how Connection builds a Collection and how ActiveQuery translates where() into the driver's query filter, everything else follows.

Implementation Patterns

ActiveRecord is the default abstraction. Use it for CRUD-heavy domain models. The lifecycle hooks (beforeSave, afterFind, afterSave) behave like the SQL AR, so event-based validation and timestamping carry over unchanged. Define every field you intend to read or write in attributes() — AR hydrates documents into public properties, and fields not listed are silently dropped on save.

Query objects map almost 1:1 onto the MongoDB filter language. yii\mongodb\ActiveQuery supports where, andWhere, orWhere, filterWhere, orderBy, limit, offset, select (projection), and distinct. Use ->select(['name', 'email']) to project; this is the MongoDB equivalent of a column list and matters more here because documents can be large. Nested conditions pass through cleanly:

User::find()->where(['status' => 'active', 'profile.city' => 'Berlin'])->all();

Drop to Command for anything AR doesn't model. Aggregation pipelines, $lookup, $facet, explain(), index management, and admin commands belong at the command/collection layer:

$collection = Yii::$app->mongodb->getCollection('orders');
$results = $collection->aggregate([
    ['$match' => ['status' => 'paid']],
    ['$group' => ['_id' => '$customer_id', 'total' => ['$sum' => '$amount']]],
]);

Use yii\mongodb\Command for database-level operations such as listCollections(), createCollection(), and distinct(). The connection exposes createCommand($document) for raw driver commands when you need something not wrapped.

Embed subdocuments with yii\mongodb\EmbeddedDocument for denormalized child records. It mirrors the ActiveRecord API but is nested inside a parent document rather than stored in its own collection. This is the idiomatic way to model one-to-few relationships and avoids $lookup in read paths.

Relations work but require discipline. hasOne/hasMany join on _id. MongoDB stores _id as an ObjectId, and the AR layer exposes it as a string on the model. When you query by a foreign key stored as a string, the driver may not match; cast the value inside the relation's link clause or store foreign keys consistently. Test relations early; they are where most bugs surface.

Migrations. Use yii\mongodb\Migration instead of yii\db\Migration for schema work. It supports createCollection, dropCollection, createIndex, and dropIndex, and integrates with the standard yii migrate command once wired into the console config.

Session and cache components. Both yii\mongodb\Cache and yii\mongodb\Session exist and are drop-in replacements. They're useful when MongoDB is already in the stack and you don't want Redis as a second dependency, but they add load to the same cluster running your application data.

GridFS for file storage. yii\mongodb\file\Collection wraps GridFS. Reach for it when you need to store binary blobs without a separate object store, but keep in mind that document-size limits and query ergonomics differ from a dedicated bucket.

Batch operations. For bulk inserts or updates, use Collection::batchInsert() and Command-level writes rather than looping save() calls. Each AR save() round-trips, so a loop over thousands of documents is an order of magnitude slower than a single batch.

Gotchas and Tips

Check your PHP and driver versions before anything else. The last tagged release was March 2018. It targets the modern mongodb extension but predates PHP 8 and MongoDB server 5.x/6.x. Expect friction if you're on a recent stack: type signatures, deprecations, and server command changes can bite. Pin the package and test against your actual server version; don't assume "it installs" means "it works."

Connection DSN quirks. The database path in the DSN is required for default collection resolution. If you connect with mongodb://host:27017 and call getCollection('users'), you'll get an error — either add /dbname or set defaultDatabaseName. Also note Connection is lazy: no socket opens until the first query, so a broken config won't surface at bootstrap.

_id is an ObjectId, not a string. The AR layer presents _id as a string in PHP, but the stored value is a BSON ObjectId. This asymmetry causes the classic bug: a raw command takes your string _id and fails to match. Fix it by wrapping in new \MongoDB\BSON\ObjectId($id) when querying at the command/collection layer.

Attributes are a whitelist, not a schema. If you add a field to a document but forget to list it in attributes(), it won't round-trip through AR. This bites hardest during incremental schema changes — new fields appear to save but vanish on the next read.

No joins, so plan your data model for reads. MongoDB has no real join cost model; $lookup in aggregation works but does full collection scans in many versions. If you're translating a normalized SQL schema, expect to rewrite hot read paths around embedding or denormalization. Decide early whether AR or Collection is your primary access layer for each model.

Transactions. Support depends on your server version and replica set configuration, and the package predates the mature multi-document transaction API. Don't design around transactions with this library; assume single-document atomicity and compensate in application code.

Debugging. Enable enableLogging and enableProfiling on the mongodb component in dev, then read the Yii debug panel's profile tab — it shows the exact driver commands sent. When a query returns nothing unexpectedly, log the command document and inspect it directly in mongosh; the AR layer sometimes mutates filters during normalization (particularly filterWhere, which skips empty values).

Indexes belong in migrations. Create indexes in yii\mongodb\Migration files, not ad hoc in shells. Production queries on unindexed fields degrade non-linearly once collections grow, and this library gives you no automatic index inference from where clauses unlike some ORMs.

Extension points worth knowing. Override ActiveRecord::collectionName() per model, subclass ActiveRecord to add a global beforeSave for audit fields, and override ActiveQuery for domain-specific scopes. The Connection class can be subclassed to inject retry logic or connection pooling options — useful when the driver's default behavior doesn't fit your cluster's topology.

Test with a real MongoDB instance. The package has no meaningful in-memory or mock backend. Integration tests against a throwaway container (or the local replica set) are the only reliable way to validate behavior, especially around ObjectId handling and aggregation pipelines.

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.
shitoudev/permissionmanager
johannesclimacus/laravel-tui
hocvt/seotools
vitalybaev/sypexgeo
amphibee/themosis-ignition
gito-me/fast-excel
frankyso/laravel-ipaymu
geolize-studio/laravel-chile
boomerangui/chat
jinas/dhivatar
store-doc/laravel-storage-driver
plus-it/laravel-translation-manager
diephp/perhaps
diephp/telegraph
osmaviation/spreadsheet
microsoft/fluentui-system-icons
mmccook/php-json-canonicalization-scheme
middlewares/firewall
qubiqx/montapacking
nyoncode/laravel-package-console