arrow_back
Back

Yii2 MongoDB extension: queries with yii2-mongodb

Andrew Dorokhov Andrew Dorokhov schedule 1 min read
menu_book Table of Contents

Extension: open_in_new yiisoft/yii2-mongodb .

It provides a Mongo-flavoured Query class (plus Active Record, migrations, and caching) with an API close to the relational Query Builder.

Queries

$query = new Query();

$search_fields = [
    'first_name' => $first_name,
    'last_name'  => $last_name,
];

if ($middle_name) {
    $search_fields['middle_name'] = [
        '$regex' => "^$middle_name",
    ];
}

$query
    ->select([
        'first_name',
        'last_name',
        'middle_name',
        'residential_address',
        'residential_city',
        'residential_state',
        'residential_zip_code',
        'phone_num',
        'birth_year',
    ])
    ->from('colorado')
    ->where($search_fields);

foreach ($query->all() as $record) {
    // ...
}

Note how a native Mongo operator ($regex) can be passed straight into the condition array.

For the database itself — shell, CRUD operators, indexes, aggregation — see the MongoDB section .

code

Need Help with Development?

Happy to help — reach out via the contacts or go straight to my Upwork profile.

work View Upwork Profile arrow_forward