## File: README.md

> [!WARNING]
> There is no official MongoDB support planned for Yii3 DB. [Use official PHP client instead](https://www.mongodb.com/docs/php-library/current/).



[](https://packagist.org/packages/yiisoft/db-mongodb)
[](https://packagist.org/packages/yiisoft/db-mongodb)
[](https://github.com/yiisoft/db-mongodb/actions?query=workflow%3Abuild)
[](https://codecov.io/gh/yiisoft/db-mongodb)
[](https://dashboard.stryker-mutator.io/reports/github.com/yiisoft/db-mongodb/master)
[](https://github.com/yiisoft/db-mongodb/actions?query=workflow%3A%22static+analysis%22)
[](https://shepherd.dev/github/yiisoft/db-mongodb)
[](https://shepherd.dev/github/yiisoft/db-mongodb)

This extension provides the [MongoDB](https://www.mongodb.com/) integration for the [Yii framework](https://www.yiiframework.com).

## Requirements

- [MongoDB PHP Extension](https://www.php.net/manual/en/set.mongodb.php) version 1.8.0 or higher.
- MongoDB server version 3.0 or higher.
- PHP 8.1 or higher.

## Installation

The package could be installed with [Composer](https://getcomposer.org):

```shell
composer require yiisoft/db-mongodb
```

## General usage

To use this extension, simply add the following code in your application configuration:

```php
return [
    //....
    'components' => [
        'mongodb' => [
            'class' => Yiisoft\Db\MongoDb\Connection::class,
            'dsn' => 'mongodb://@localhost:27017/mydatabase',
            'options' => [
                "username" => "Username",
                "password" => "Password"
            ]
        ],
    ],
];
```

Once you have a MongoDB connection instance, you can execute a MongoDB commands and queries
using `Yiisoft\Db\MongoDb\Command`:

```php
// execute command:
$result = Yii::$app->mongodb->createCommand(['listIndexes' => 'some_collection'])->execute();

// execute query (find):
$cursor = Yii::$app->mongodb->createCommand(['projection' => ['name' => true]])->query('some_collection');

// execute batch (bulk) operations:
Yii::$app->mongodb->createCommand()
    ->addInsert(['name' => 'new'])
    ->addUpdate(['name' => 'existing'], ['name' => 'updated'])
    ->addDelete(['name' => 'old'])
    ->executeBatch('customer');
```

Using the connection instance you may access databases and collections.
Most of the MongoDB commands are accessible via `\Yiisoft\Db\MongoDb\Collection` instance:

```php
$collection = Yii::$app->mongodb->getCollection('customer');
$collection->insert(['name' => 'John Smith', 'status' => 1]);
```

To perform `find` queries, you should use `\Yiisoft\Db\MongoDb\Query`:

```php
use Yiisoft\Db\MongoDb\Query;

$query = new Query();
// compose the query
$query->select(['name', 'status'])
    ->from('customer')
    ->limit(10);
// execute the query
$rows = $query->all();
```

## Documentation

- Guide: [English](docs/guide/en/README.md), [Français](docs/guide/fr/README.md), [Русский](docs/guide/ru/README.md), [日本語](docs/guide/ja/README.md)
- [Internals](docs/internals.md)

If you need help or have a question, the [Yii Forum](https://forum.yiiframework.com/c/yii-3-0/63) is a good place for that.
You may also check out other [Yii Community Resources](https://www.yiiframework.com/community).

## License

The Yii Database MongoDB driver is free software. It is released under the terms of the BSD License.
Please see [`LICENSE`](./LICENSE.md) for more information.

Maintained by [Yii Software](https://www.yiiframework.com/).

## Support the project

[](https://opencollective.com/yiisoft)

## Follow updates

[](https://www.yiiframework.com/)
[](https://twitter.com/yiiframework)
[](https://t.me/yii3en)
[](https://www.facebook.com/groups/yiitalk)
[](https://yiiframework.com/go/slack)

---

## File: CHANGELOG.md

# Yii Framework MongoDB extension Change Log

## 1.0.0 under development

- Initial release.

---

## File: composer.json

{
    "name": "yiisoft/db-mongodb",
    "description": "Yii Framework MongoDB extension",
    "keywords": [
        "yii",
        "mongo",
        "mongodb",
        "gridfs"
    ],
    "type": "library",
    "license": "BSD-3-Clause",
    "support": {
        "issues": "https://github.com/yiisoft/db-mongodb/issues?state=open",
        "source": "https://github.com/yiisoft/db-mongodb",
        "forum": "https://www.yiiframework.com/forum/",
        "wiki": "https://www.yiiframework.com/wiki/",
        "irc": "ircs://irc.libera.chat:6697/yii",
        "chat": "https://t.me/yii3en"
    },
    "funding": [
        {
            "type": "opencollective",
            "url": "https://opencollective.com/yiisoft"
        },
        {
            "type": "github",
            "url": "https://github.com/sponsors/yiisoft"
        }
    ],
    "authors": [
        {
            "name": "Paul Klimov",
            "email": "klimov.paul@gmail.com"
        }
    ],
    "require": {
        "php": "^8.1",
        "ext-mongodb": ">=1.8.0"
    },
    "require-dev": {
        "friendsofphp/php-cs-fixer": "^3.92.5",
        "rector/rector": "^2.3.1",
        "phpunit/phpunit": "^9.5|^10.0",
        "roave/infection-static-analysis-plugin": "^1.6",
        "spatie/phpunit-watcher": "^1.23",
        "vimeo/psalm": "^5.20",
        "yiisoft/arrays": "^2.0|^3.0",
        "yiisoft/cache": "^1.0",
        "yiisoft/di": "dev-master",
        "yiisoft/factory": "^1.0",
        "yiisoft/log": "^1.0",
        "yiisoft/strings": "^2.0",
        "yiisoft/var-dumper": "^1.0"
    },
    "autoload": {
        "psr-4": {
            "Yiisoft\\Db\\MongoDb\\": "src"
        }
    },
    "autoload-dev": {
        "psr-4": {
            "Yiisoft\\Db\\MongoDb\\Tests\\": "tests"
        }
    },
    "extra": {
        "branch-alias": {
            "dev-master": "1.0.x-dev"
        }
    },
    "config": {
        "sort-packages": true,
        "allow-plugins": {
            "infection/extension-installer": true
        }
    },
    "minimum-stability": "dev",
    "prefer-stable": true,
    "scripts": {
        "test": "phpunit --testdox --no-interaction",
        "test-watch": "phpunit-watcher watch"
    }
}

---

## File: docker-compose.yaml

version: '3.8'

services:
  db-mongodb-php:
    container_name: db-mongodb-php
    hostname: db-mongodb-php
    build:
      context: .
      dockerfile: Dockerfile
      args:
        PHP_VERSION: ${PHP_VERSION:-8.1}
    volumes:
      - .:/code
    networks: &network
      - db-mongodb-network

  db-mongodb-db:
    image: mongo
    container_name: db-mongodb-db
    restart: always
    environment:
      MONGO_INITDB_ROOT_USERNAME: root
      MONGO_INITDB_ROOT_PASSWORD: password
    networks: *network

networks:
  db-mongodb-network:
    driver: bridge
    ipam:
      config:
        - subnet: 172.20.0.0/16

---

## File: LICENSE.md

Copyright © 2008 by Yii Software (https://www.yiiframework.com/)
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

 * Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in
   the documentation and/or other materials provided with the
   distribution.
 * Neither the name of Yii Software nor the names of its
   contributors may be used to endorse or promote products derived
   from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

---

## File: .phpunit-watcher.yml

watch:
    directories:
        - src
        - tests
    fileMask: '*.php'
notifications:
    passingTests: false
    failingTests: false
phpunit:
    binaryPath: vendor/bin/phpunit
    timeout: 180

---

## File: docs/internals.md

# Internals

## Unit testing

The package is tested with [PHPUnit](https://phpunit.de/). To run tests:

```shell
./vendor/bin/phpunit
```

## Mutation testing

The package tests are checked with [Infection](https://infection.github.io/) mutation framework with
[Infection Static Analysis Plugin](https://github.com/Roave/infection-static-analysis-plugin). To run it:

```shell
./vendor/bin/roave-infection-static-analysis-plugin
```

## Static analysis

The code is statically analyzed with [Psalm](https://psalm.dev/). To run static analysis:

```shell
./vendor/bin/psalm
```

---

## File: docs/guide/en/README.md

# Yii MongoDB Extension

## General usage

- [MongoId specifics](usage-mongoid.md)
- [Using the MongoDB ActiveRecord](usage-ar.md)
- [Working with embedded documents](usage-embedded-documents.md)
- [Aggregation](usage-aggregation.md)
- [Using GridFS](usage-gridfs.md)

## Additional topics

- [Logging and Profiling](topics-logging.md)
- [Using the Cache component](topics-cache.md)
- [Using the Session component](topics-session.md)
- [Using the I18N Message Source](topics-i18n-message-source.md)
- [Using Gii generator](topics-gii.md)
- [Using the MongoDB DebugPanel](topics-debug.md)
- [Using Migrations](topics-migrations.md)

---

## File: docs/guide/en/topics-cache.md

# Using the Cache component

To use the [Yii Caching Library](https://github.com/yiisoft/cache), in addition to configuring the connection as described in [General usage](../../../README.md#general-usage) section,
you also have to configure the `cache` component to be `Yiisoft\Db\MongoDb\Cache`:

```php
return [
    //....
    'components' => [
        // ...
        'cache' => [
            'class' => yii\caching\Cache::class,
            'handler' => [
                'class' => Yiisoft\Db\MongoDb\Cache::class,
            ],
        ],
    ]
];
```

---

## File: docs/guide/en/topics-debug.md

# Using the MongoDB DebugPanel

The Yii MongoDB Extension provides a debug panel that can be integrated with the [Yii Debug Extension](https://github.com/yiisoft/yii-debug)
and shows the executed MongoDB queries.

Add the following to you application config to enable it (if you already have the [Yii Debug Extension](https://github.com/yiisoft/yii-debug)
enabled, it is sufficient to just add the panels configuration):

```php
    // ...
    'bootstrap' => ['debug'],
    'modules' => [
        'debug' => [
            'class' => yii\debug\Module::class,
            'panels' => [
                'mongodb' => [
                    'class' => Yiisoft\Db\MongoDb\Debug\MongoDbPanel::class,
                    // 'db' => 'mongodb', // MongoDB component ID, defaults to `db`. Uncomment and change this line, if you registered MongoDB component with a different ID.
                ],
            ],
        ],
    ],
    // ...
```

---

## File: docs/guide/en/topics-gii.md

# Using Gii generator

This extension provides a code generator, which can be integrated with [Yii Gii generator](https://github.com/yiisoft/yii-gii). It allows generation of the
Active Record code. In order to enable it, you should adjust your application configuration in following way:

```php
return [
    //....
    'modules' => [
        // ...
        'gii' => [
            'class' => Yiisoft\Yii\Gii\Module::class,
            'generators' => [
                'mongoDbModel' => [
                    'class' => Yiisoft\Db\MongoDb\Gii\Model\Generator::class,
                ]
            ],
        ],
    ]
];
```

> Note: since MongoDB is schemaless, there is not much information, which generated code may base on. So generated code
  is very basic and definitely requires adjustments.

---

## File: docs/guide/en/topics-i18n-message-source.md

# Using the I18N Message Source

You may use `\Yiisoft\Db\MongoDb\i18n\MongoDbMessageSource` for the i18n message translations storage.
Application configuration example:

```php
return [
    //....
    'components' => [
        // ...
        'i18n' => [
            'translations' => [
                '*' => [
                    'class' => Yiisoft\Db\MongoDb\i18n\MongoDbMessageSource::class
                ]
            ]
        ],
    ]
];
```

`\Yiisoft\Db\MongoDb\i18n\MongoDbMessageSource` uses single collection to store all translations.
Each entry in this collection should have 3 fields:

 - language: string, translation language
 - category: string, name translation category
 - messages: array, list of actual message translations, in each element: the `message` key is raw message name
   and 'translation' key - message translation.

For example:

```json
{
    "category": "app",
    "language": "de",
    "messages": [
        {
            "message": "Hello world!",
            "translation": "Hallo Welt!"
        },
        {
            "message": "The dog runs fast.",
            "translation": "Der Hund rennt schnell.",
        },
        ...
    ],
}
```

You also can specify `messages` using source message as a direct BSON key, while its value holds the translation.
For example:

```json
{
    "category": "app",
    "language": "de",
    "messages": {
        "Hello world!": "Hallo Welt!",
        "See more": "Mehr sehen",
        ...
    },
}
```

However such approach is not recommended as BSON keys can not contain symbols like `.` or `$`.

Please refer to `\Yiisoft\Db\MongoDb\i18n\MongoDbMessageSource` for more details about configuration and translation
collection data structure.

---

## File: docs/guide/en/topics-logging.md

# Logging and Profiling

This extension provides logging for executed commands or queries.
Logging is optional and can be enabled or disabled at `\Yiisoft\Db\MongoDb\Connection` level:

```php
return [
    //....
    'components' => [
        'mongodb' => [
            'class' => Yiisoft\Db\MongoDb\Connection::class,
            'dsn' => 'mongodb://developer:password@localhost:27017/mydatabase',
            'enableLogging' => true, // enable logging
            'enableProfiling' => true, // enable profiling
        ],
    ],
];
```

> Note: log messages generated for the commands and queries do not contain actual
> text of the performed queries, they contains only a **close approximation** of it,
> composed on the values which can be extracted from PHP MongoDB extension classes.
> If you need to see actual query text, you should use specific tools for that.

> Tip: Keep in mind that composition of the log messages take some time and program resources.
> Thus it make sense to disable logging at the production environment.

---

## File: docs/guide/en/topics-migrations.md

# Using Migrations

MongoDB is schemaless and will create any missing collection on the first demand. However there are many cases, when
you may need applying persistent changes to the MongoDB database. For example: you may need to create a collection with
some specific options or create indexes.
MongoDB migrations are managed with `Yiisoft\Db\MongoDb\Console\Controllers\MigrateController`, which is an analog of regular
`\Yiisoft\Yii\Console\Controllers\MigrateController`.

In order to enable this command you should adjust the configuration of your console application:

```php
return [
    // ...
    'controllerMap' => [
        'mongodb-migrate' => 'Yiisoft\Db\MongoDb\Console\Controllers\MigrateController'
    ],
];
```

Below are some common usages of this command:

```shell
# creates a new migration named 'create_user_collection'
./yii mongodb-migrate/create create_user_collection

# applies ALL new migrations
./yii mongodb-migrate

# reverts the last applied migration
./yii mongodb-migrate/down
```

---

## File: docs/guide/en/topics-session.md

# Using the Session component

To use the `Session` component, in addition to configuring the connection as described in [General usage](../../../README.md#general-usage) section,
you also have to configure the `session` component to be `Yiisoft\Db\MongoDb\Session`:

```php
return [
    //....
    'components' => [
        // ...
        'session' => [
            'class' => Yiisoft\Db\MongoDb\Session::class,
        ],
    ]
];
```

---

## File: docs/guide/en/usage-aggregation.md

# Aggregation

This extension provides support for the [MongoDB aggregation functionality](https://docs.mongodb.com/manual/aggregation/) wrapping corresponding commands into PHP methods of `\Yiisoft\Db\MongoDb\Command`.

## Single Purpose Aggregation Operations

The simplest MongoDB aggregation operations are `count` and `distinct`, which are available via `\Yiisoft\Db\MongoDb\Command::count()`
and `\Yiisoft\Db\MongoDb\Command::distinct()` correspondingly. For example:

```php
$booksCount = Yii::$app->mongodb->createCommand()->count('books', ['category' => 'programming']);
```

You may as well use `\Yiisoft\Db\MongoDb\Collection::count()` and `\Yiisoft\Db\MongoDb\Collection::distinct()` shortcut methods:

```php
$booksCount = Yii::$app->mongodb->getCollection('books')->count(['category' => 'programming']);
```

Methods `count()` and `distinct()` are also available at `\Yiisoft\Db\MongoDb\Query` class:

```php
$booksCount = (new Query())
    ->from('books')
    ->where(['category' => 'programming'])
    ->count();
```

## Pipeline

[Aggregation Pipeline](https://docs.mongodb.com/manual/core/aggregation-pipeline/) can be executed with `\Yiisoft\Db\MongoDb\Command::aggregate()`.
The following example display how you can group books by `authorId` field:

```php
$authors = Yii::$app->mongodb->createCommand()->aggregate('books', [
    [
        '$group' => [
            '_id' => '$authorId',
        ],
    ],
]);
```

You may as well use `\Yiisoft\Db\MongoDb\Collection::aggregate()` as shortcut.
In the following example we are grouping books by both `authorId` and `category` fields:

```php
$collection = Yii::$app->mongodb->getCollection('books');
$authors = $collection->aggregate([
    [
        '$group'   => [
            '_id'      => '$authorId',
            'category' => '$category',
        ],
    ],
]);
```

Multiple pipelines can be specified for more sophisticated aggregation.
In the following example we are grouping books by `authorId` field, sorting them by `createdAt` field descending
and then we are limiting the result to 100 documents skipping first 300 records.

```php
$collection = Yii::$app->mongodb->getCollection('books');
$authors = $collection->aggregate([
    [
        '$match' => [
            'name' => ['$ne' => ''],
        ],
    ],
    [
        '$group' => [
            '_id' => '$authorId',
        ],
    ],
    [
        '$sort' => ['createdAt' => -1]
    ],
    [
        '$skip' => 300
    ],
    [
        '$limit' => 100
    ],
]);
```

Please refer to [MongoDB Aggregation Pipeline Docs](https://docs.mongodb.com/manual/core/aggregation-pipeline/) for detailed information
about pipeline specifications.


## Aggregation via `\Yiisoft\Db\MongoDb\Query`

Simple aggregations can be performed via following methods of the [[\Yiisoft\Db\MongoDb\Query]] class:

 - `sum()` - returns the sum of the specified column values.
 - `average()` - returns the average of the specified column values.
 - `min()` - returns the minimum of the specified column values.
 - `max()` - returns the maximum of the specified column values.

In case of these methods invocation `\Yiisoft\Db\MongoDb\Query::$where` will be used for `$match` pipeline composition.

```php
use Yiisoft\Db\MongoDb\Query;

$maxPrice = (new Query())
    ->from('books')
    ->where(['name' => ['$ne' => '']])
    ->max('price', $db);
```


## Map Reduce

[Map Reduce](https://docs.mongodb.com/manual/core/map-reduce/) can be executed with `\Yiisoft\Db\MongoDb\Command::mapReduce()`.

```php
$result = Yii::$app->mongodb->createCommand()->mapReduce('books',
    'function () {emit(this.status, this.amount)}',
    'function (key, values) {return Array.sum(values)}',
    'mapReduceOut',
    ['status' => ['$lt' => 3]]
);
```

You may as well use `\Yiisoft\Db\MongoDb\Collection::mapReduce()` as shortcut.

```php
$result = Yii::$app->mongodb->getCollection('books')->mapReduce(
    'function () {emit(this.status, this.amount)}',
    'function (key, values) {return Array.sum(values)}',
    'mapReduceOut',
    ['status' => ['$lt' => 3]]
);
```

---

## File: docs/guide/en/usage-ar.md

# Using the MongoDB ActiveRecord

This extension provides ActiveRecord solution similar ot the `\Yiisoft\Db\ActiveRecord`.
To declare an ActiveRecord class you need to extend `\Yiisoft\Db\MongoDb\ActiveRecord` and
implement the `collectionName` and `attributes` methods:

```php
use Yiisoft\Db\MongoDb\ActiveRecord;

class Customer extends ActiveRecord
{
    /**
     * @return string the name of the index associated with this ActiveRecord class.
     */
    public static function collectionName()
    {
        return 'customer';
    }

    /**
     * @return array list of attribute names.
     */
    public function attributes()
    {
        return ['_id', 'name', 'email', 'address', 'status'];
    }
}
```

**Note:** collection primary key name `_id` should be always explicitly setup as an attribute.

You can use `\yii\data\ActiveDataProvider` with `\Yiisoft\Db\MongoDb\Query` and `\Yiisoft\Db\MongoDb\ActiveQuery`:

```php
use yii\data\ActiveDataProvider;
use Yiisoft\Db\MongoDb\Query;

$query = new Query();
$query->from('customer')->where(['status' => 2]);
$provider = new ActiveDataProvider([
    'query' => $query,
    'pagination' => [
        'pageSize' => 10,
    ]
]);
$models = $provider->getModels();
```

```php
use yii\data\ActiveDataProvider;
use app\models\Customer;

$provider = new ActiveDataProvider([
    'query' => Customer::find(),
    'pagination' => [
        'pageSize' => 10,
    ]
]);
$models = $provider->getModels();
```

---

## File: docs/guide/en/usage-embedded-documents.md

# Working with embedded documents

This extension does not provide any special way to work with embedded documents (sub-documents) at the moment.
General recommendation is avoiding it if possible.
For example, instead of:

```php
{
    content: "some content",
    author: {
        name: author1,
        email: author1@domain.com
    }
}
```

use following:

```php
{
    content: "some content",
    author_name: author1,
    author_email: author1@domain.com
}
```

Yii Model designed assuming single attribute is a scalar. Validation and attribute processing based on this suggestion.
Still any attribute can be an array of any depth and complexity, however you should handle its validation on your own.

While there is no explicit support for embedded documents, there is also no explicit restriction on it.
You may create your own solution or use third-party extension like [yii2tech/embedded](https://github.com/yii2tech/embedded)
for this feature.

> **Note:** The [yii2tech/embedded](https://github.com/yii2tech/embedded) repository has been archived by the owner on Jan 10, 2022. It is now read-only.

---

## File: docs/guide/en/usage-gridfs.md

# Using GridFS

This extension supports [MongoGridFS](https://docs.mongodb.com/manual/core/gridfs/) via
classes under namespace `\Yiisoft\Db\MongoDb\File`.
There you will find specific Collection, Query and ActiveRecord classes.

You can upload a file using `\Yiisoft\Db\MongoDb\File\Upload`:

```php
$document = Yii::$app->mongodb->getFileCollection()->createUpload()
    ->addContent('Part 1')
    ->addContent('Part 2')
    // ...
    ->complete();
```

You can download the file using `\Yiisoft\Db\MongoDb\File\Download`:

```php
Yii::$app->mongodb->getFileCollection()->createDownload($document['_id'])->toFile('/path/to/file.dat');
```

Each row of the file query result contains `\Yiisoft\Db\MongoDb\File\Download` instance at the key `file`:

```php
use Yiisoft\Db\MongoDb\File\Query;

$query = new Query();
$rows = $query->from('fs')
    ->limit(10)
    ->all();

foreach ($rows as $row) {
    var_dump($row['file']); // outputs: "object(\Yiisoft\Db\MongoDb\File\Download)"
    echo $row['file']->toString(); // outputs file content
}
```

Using `\Yiisoft\Db\MongoDb\File\ActiveRecord` you can manipulate the file using `file` property:

```php
use Yiisoft\Db\MongoDb\File\ActiveRecord;

class ImageFile extends ActiveRecord
{
    //...
}

$record = new ImageFile();
$record->number = 15;
$record->file = '/path/to/some/file.jpg'; // upload local file to GridFS
$record->save();

$record = ImageFile::find()->where(['number' => 15])->one();
var_dump($record->file); // outputs: "object(\Yiisoft\Db\MongoDb\File\Download)"
echo $row['file']->toString(); // outputs file content
```

You may as well operate GridFS files via regular PHP stream resource.
You will need to register a stream wrapper provided by this extension, `\Yiisoft\Db\MongoDb\File\StreamWrapper`.
This can be done via `\Yiisoft\Db\MongoDb\File\Connection::registerFileStreamWrapper()`.
Once stream wrapper is registered, you may open a stream resource using following format:

```php
'protocol://databaseName.fileCollectionPrefix?file_attribute=value'
```

For example:

```php
Yii::$app->mongodb->registerFileStreamWrapper(); // register stream wrapper

// write a file:
$resource = fopen('gridfs://mydatabase.fs?filename=new_file.txt', 'w');
fwrite($resource, 'some content');
// ...
fclose($resource);

// write file with several fields:
$resource = fopen('gridfs://mydatabase.fs?filename=new_file.txt&number=17&status=active', 'w');
fwrite($resource, 'file number 17 with status "active"');
fclose($resource);

// read a file:
$resource = fopen('gridfs://mydatabase.fs?filename=my_file.txt', 'r');
$fileContent = stream_get_contents($resource);
```

---

## File: docs/guide/en/usage-mongoid.md

# MongoId specifics

## Getting scalar from document ID

> **Remember:** MongoDB document id (`_id` field) is not scalar, but an instance of `\MongoDB\BSON\ObjectID` class.
> To get actual Mongo ID string your should typecast `\MongoDB\BSON\ObjectID` instance to string:

```php
$query = new Query();
$row = $query->from('customer')->one();
var_dump($row['_id']); // outputs: "object(\MongoDB\BSON\ObjectID)"
var_dump((string) $row['_id']); // outputs "string 'acdfgdacdhcbdafa'"
```

Although this fact is very useful sometimes, it often produces some problems.
You may face them in URL composition or attempt of saving `_id` to other storage.
In these cases, ensure you have converted `\MongoDB\BSON\ObjectID` into the string:

```php
/* @var $this yii\web\View */
echo $this->createUrl(['item/update', 'id' => (string) $row['_id']]);
```

Same applies to implementing user identity which is stored in MongoDB. When implementing
`\yii\web\IdentityInterface::getId()` you should typecast `\MongoDB\BSON\ObjectID` class to scalar
in order for authentication to work.

## Getting document ID from scalar

While building condition, values for the key `_id` will be automatically cast to `\MongoDB\BSON\ObjectID`
instance, even if they are plain strings. So it is not necessary for you to perform back cast of string `_id`
representation:

```php
use yii\web\Controller;
use Yiisoft\Db\MongoDb\Query;

class ItemController extends Controller
{
    /**
     * @param string $id MongoId string (not object)
     */
    public function actionUpdate($id)
    {
        $query = new Query;
        $row = $query->from('item')
            ->where(['_id' => $id]) // implicit typecast to [[\MongoDB\BSON\ObjectID]]
            ->one();
        ...
    }
}
```

However, if you have other columns, containing `\MongoDB\BSON\ObjectID`, you
should take care of possible typecast on your own.

---

## File: docs/guide/fr/README.md

MongoDB Extension for Yii 2
===========================

cet extention vous permet l'integration de [MongoDB](https://www.mongodb.com/) pour Yii2 framework.

Mise en Route
---------------

* [Installation](installation.md)
* [Simple Utilisation](basic-usage.md)

---

## File: docs/guide/fr/basic-usage.md

Utilisation Basic
=================

Une fois tu as une connection a MongoDB machine, tu peux executer ces commandes et requettes en utiisant 
[[Yiisoft\Db\MongoDb\Command]]:

```php
// execute command:
$result = Yii::$app->mongodb->createCommand(['listIndexes' => 'some_collection'])->execute();

// execute query (find):
$cursor = Yii::$app->mongodb->createCommand(['projection' => ['name' => true]])->query('some_collection');

// execute batch (bulk) operations:
Yii::$app->mongodb->createCommand()
    ->addInsert(['name' => 'new'])
    ->addUpdate(['name' => 'existing'], ['name' => 'updated'])
    ->addDelete(['name' => 'old'])
    ->executeBatch('customer');
```

En utilisant l'instance de connection, tu peux acceder a les bases de donnee ansi a les collections.
La plupart des commandes de MongoDb sont accessible via [[\Yiisoft\Db\MongoDb\Collection]] instance: 

```php
$collection = Yii::$app->mongodb->getCollection('customer');
$collection->insert(['name' => 'John Smith', 'status' => 1]);
```

Pour effectuer une requette de recherche "find", tu dois utiliser [[\Yiisoft\Db\MongoDb\Query]]: 

```php
use Yiisoft\Db\MongoDb\Query;

$query = new Query();
// compose the query
$query->select(['name', 'status'])
    ->from('customer')
    ->limit(10);
// execute the query
$rows = $query->all();
```

---

## File: docs/guide/fr/installation.md

Installation
============

## Requirements

l'extention  [MongoDB PHP Extension](https://www.php.net/manual/fr/set.mongodb.php) version 1.0.0 ou plus.

## Installation du composer:

Il est preferable d'installer composer depuis :  [composer](https://getcomposer.org/download/).

et puis executer la commande: 

```
composer require yiisoft/yii2-mongodb
```

ou bien ajouter : 

```
"yiisoft/yii2-mongodb": "~2.1.0"
```

a la section `require` de votre `composer.json`.

## Configuration de votre application

Pour l'utilisation de cette extention, il suffit d'ajouter le code suivant a configuration de votre application:

```php
return [
    //....
    'components' => [
        'mongodb' => [
            'class' => Yiisoft\Db\MongoDb\Connection::class,
            'dsn' => 'mongodb://developer:password@localhost:27017/mydatabase',
        ],
    ],
];
```

---

## File: docs/guide/ja/README.md

[Binary file]

---

## File: docs/guide/ja/basic-usage.md

基本的な使用方法
================

接続のインスタンスを使用して、データベースとコレクションにアクセスすることが出来ます。
ほとんどの MongoDB コマンドに [[\Yiisoft\Db\MongoDb\Collection]] によってアクセスすることが出来ます。

```php
$collection = Yii::$app->mongodb->getCollection('customer');
$collection->insert(['name' => 'John Smith', 'status' => 1]);
```

"find" クエリを実行するためには、[[\Yiisoft\Db\MongoDb\Query]] を使わなければなりません。

```php
use Yiisoft\Db\MongoDb\Query;

$query = new Query();
// クエリを構築する
$query->select(['name', 'status'])
    ->from('customer')
    ->limit(10);
// クエリを実行する
$rows = $query->all();
```

このエクステンションは、ロギングとプロファイリングをサポートしています。
ただし、ログメッセージは実行されたクエリの実際のテキストを含んでいません。
ログメッセージは PHP Mongo 拡張のクラスから抽出することが出来る値から構成された、クエリテキストの「近似値」しか含んでいません。
実際のクエリテキストを見るためには、そのための特別なツールを使用する必要があります。

---

## File: docs/guide/ja/installation.md

インストール
============

## 必要条件

このエクステンションは [MongoDB PHP 拡張](https://www.php.net/manual/ja/set.mongodb.php) バージョン 1.0.0 以降を必要とします。

## Composer パッケージを取得する

このエクステンションをインストールするのに推奨される方法は [composer](https://getcomposer.org/download/) によるものです。

下記のコマンドを実行してください。

```
composer require yiisoft/yii2-mongodb
```

または、あなたの `composer.json` ファイルの `require` セクションに、下記を追加してください。

```
"yiisoft/yii2-mongodb": "~2.1.0"
```

## アプリケーションを構成する

このエクステンションを使用するために必要なことは、下記のコードをあなたのアプリケーション構成情報に追加することだけです。

```php
return [
    //....
    'components' => [
        'mongodb' => [
            'class' => '\Yiisoft\Db\MongoDb\Connection',
            'dsn' => 'mongodb://developer:password@localhost:27017/mydatabase',
        ],
    ],
];
```

---

## File: docs/guide/ja/topics-cache.md

キャッシュコンポーネントを使用する
==================================

`Cache` コンポーネントを使用するためには、[インストール](installation.md) の節で説明した接続の構成に加えて、`cache` コンポーネントを `Yiisoft\Db\MongoDb\Cache` として構成する必要があります。

```php
return [
    //....
    'components' => [
        // ...
        'cache' => [
            'class' => 'Yiisoft\Db\MongoDb\Cache',
        ],
    ]
];
```

---

## File: docs/guide/ja/topics-debug.md

[Binary file]

---

## File: docs/guide/ja/topics-gii.md

[Binary file]

---

## File: docs/guide/ja/topics-i18n-message-source.md

I18N メッセージソースを使用する
===============================

[[\Yiisoft\Db\MongoDb\i18n\MongoDbMessageSource]] を i18n メッセージ翻訳ストレージとして使用することができます。
アプリケーション構成の例:

```php
return [
    //....
    'components' => [
        // ...
        'i18n' => [
            'translations' => [
                '*' => [
                    'class' => 'Yiisoft\Db\MongoDb\i18n\MongoDbMessageSource'
                ]
            ]
        ],
    ]
];
```


構成と翻訳コレクションのデータ構造に関する詳細は [[\Yiisoft\Db\MongoDb\i18n\MongoDbMessageSource]] を参照してください。

---

## File: docs/guide/ja/topics-logging.md

ロギングとプロファイリング
==========================

このエクステンションは、実行されたコマンドまたはクエリのロギングを提供しています。
ロギングは選択可能で、[[\Yiisoft\Db\MongoDb\Connection]] レベルで有効または無効にすることが出来ます。

```php
return [
    //....
    'components' => [
        'mongodb' => [
            'class' => '\Yiisoft\Db\MongoDb\Connection',
            'dsn' => 'mongodb://developer:password@localhost:27017/mydatabase',
            'enableLogging' => true, // ロギングを有効にする
            'enableProfiling' => true, // プロファイリングを有効にする
        ],
    ],
];
```

> Note: コマンドとクエリに対して生成されるログメッセージは、実行されたクエリの実際のテキストは含みません。
  それは、PHP MongoDB エクステンションクラスから抽出可能な値から作成された **クエリの近似値** しか含みません。
  実際のクエリのテキストを見る必要がある場合は、そのための専用のツールを使わなければなりません。

> Tip: ログメッセージの作成には、いくらか時間とプログラムリソースがかかるということを忘れないで下さい。
  従って、実運用環境でロギングを無効にするのは、道理にかなったことです。

---

## File: docs/guide/ja/topics-migrations.md

マイグレーションを使用する
==========================

MongoDB はスキーマレスであり、欠落しているコレクションはすべて最初に要求されたときに作成されます。
しかし、MongoDB データベースに永続的な変更を適用する必要があることはよくあります。
例えば、何らかの特定のオプションを指定してコレクションを作成したり、インデックスを作成したりする場合です。
MongoDB のマイグレーションは [[Yiisoft\Db\MongoDb\Console\Controllers\MigrateController]] によって管理されます。
これは通常の [[\Yiisoft\Yii\Console\Controllers\MigrateController]] に類似したものです。

このコマンドを有効にするためには、コンソールアプリケーションの構成を次のように修正しなければなりません。

```php
return [
    // ...
    'controllerMap' => [
        'mongodb-migrate' => 'Yiisoft\Db\MongoDb\Console\Controllers\MigrateController'
    ],
];
```

以下に、このコマンドのよくある使用方法をいくつか示します。

```
# 'create_user_collection' という名前の新しいマイグレーションを作成する
yii mongodb-migrate/create create_user_collection

# 全ての新しいマイグレーションを適用する
yii mongodb-migrate

# 最後に適用されたマイグレーションを取り消す
yii mongodb-migrate/down
```

---

## File: docs/guide/ja/topics-session.md

セッションコンポーネントを使用する
==================================

`Session` コンポーネントを使用するためには、[インストール](installation.md) の節で説明した接続の構成に加えて、`session` コンポーネントを `Yiisoft\Db\MongoDb\Session` として構成する必要があります。

```php
return [
    //....
    'components' => [
        // ...
        'session' => [
            'class' => 'Yiisoft\Db\MongoDb\Session',
        ],
    ]
];
```

---

## File: docs/guide/ja/usage-ar.md

[Binary file]

---

## File: docs/guide/ja/usage-embedded-documents.md

[Binary file]

---

## File: docs/guide/ja/usage-gridfs.md

GridFS を使用する
=================

このエクステンションは、名前空間 "\Yiisoft\Db\MongoDb\File" の下にある諸クラスによって [MongoGridFS](https://docs.mongodb.com/manual/core/gridfs/) をサポートしています。
そこに　GridFS のためのコレクション、クエリ、アクティブレコードのクラスがあります。

[[\Yiisoft\Db\MongoDb\File\Upload]] を使ってファイルをアップロードすることが出来ます。

```php
$document = Yii::$app->mongodb->getFileCollection()->createUpload()
    ->addContent('Part 1')
    ->addContent('Part 2')
    // ...
    ->complete();
```

[[\Yiisoft\Db\MongoDb\File\Download]] を使ってファイルをダウンロードすることが出来ます。

```php
Yii::$app->mongodb->getFileCollection()->createDownload($document['_id'])->toFile('/path/to/file.dat');
```

ファイルクエリの結果の各行は、'file' というキーで [[\Yiisoft\Db\MongoDb\File\Download]] のインスタンスを含みます。

```php
use Yiisoft\Db\MongoDb\File\Query;

$query = new Query();
$rows = $query->from('fs')
    ->limit(10)
    ->all();

foreach ($rows as $row) {
    var_dump($row['file']); // 出力: "object(\Yiisoft\Db\MongoDb\File\Download)"
    echo $row['file']->toString(); // ファイルのコンテントを出力
}
```

[\Yiisoft\Db\MongoDb\File\ActiveRecord]] を使うと、'file' プロパティを使ってファイルを操作することが出来ます。

```php
use Yiisoft\Db\MongoDb\File\ActiveRecord;

class ImageFile extends ActiveRecord
{
    //...
}

$record = new ImageFile();
$record->number = 15;
$record->file = '/path/to/some/file.jpg'; // ローカルのファイルを GridFS にアップロード
$record->save();

$record = ImageFile::find()->where(['number' => 15])->one();
var_dump($record->file); // 出力: "object(\Yiisoft\Db\MongoDb\File\Download)"
echo $row['file']->toString(); // ファイルのコンテントを出力
```

GridFS のファイルを通常の PHP ストリームリソースを通じて操作することも出来ます。
そのためには、このエクステンションによって提供されるストリームラッパー [[\Yiisoft\Db\MongoDb\File\StreamWrapper]] を登録する必要があります。
登録は [[\Yiisoft\Db\MongoDb\File\Connection::registerFileStreamWrapper()]] によって行うことが出来ます。
ストリームラッパーを登録すれば、次のフォーマットを使ってストリームリソースをオープンすることが出来ます。

```
'protocol://databaseName.fileCollectionPrefix?file_attribute=value'
```

例えば、

```php
Yii::$app->mongodb->registerFileStreamWrapper(); // ストリームラッパーを登録

// ファイルを書き込む
$resource = fopen('gridfs://mydatabase.fs?filename=new_file.txt', 'w');
fwrite($resource, '何らかのコンテント');
// ...
fclose($resource);

// いくつかのフィールドを持つファイルを書き込む
$resource = fopen('gridfs://mydatabase.fs?filename=new_file.txt&number=17&status=active', 'w');
fwrite($resource, 'ファイル番号 = 17, ステータス = "active"');
fclose($resource);

// ファイルを読み出す
$resource = fopen('gridfs://mydatabase.fs?filename=my_file.txt', 'r');
$fileContent = stream_get_contents($resource);
```

---

## File: docs/guide/ja/usage-mongoid.md

[Binary file]

---

## File: docs/guide/ru/README.md

[Binary file]

---

## File: docs/guide/ru/basic-usage.md

Основы использования
===========

После установки экземпляра соединения с MongoDB, вы можете выполнять MongoDB команды и запросы
используя [[Yiisoft\Db\MongoDb\Command]]:

```php
// выполнить команду:
$result = Yii::$app->mongodb->createCommand(['listIndexes' => 'some_collection'])->execute();

// выполнить запрос (find):
$cursor = Yii::$app->mongodb->createCommand(['projection' => ['name' => true]])->query('some_collection');

// выполнить пакетную операцию:
Yii::$app->mongodb->createCommand()
    ->addInsert(['name' => 'new'])
    ->addUpdate(['name' => 'existing'], ['name' => 'updated'])
    ->addDelete(['name' => 'old'])
    ->executeBatch('customer');
```

Используя экземпляр соединения, вы можете получить доступ к базам данным и коллекциям.
Большинство MongoDB команд доступны через [[\Yiisoft\Db\MongoDb\Collection]] например:

```php
$collection = Yii::$app->mongodb->getCollection('customer');
$collection->insert(['name' => 'John Smith', 'status' => 1]);
```

Для выполнения `find` запросов, вы должны использовать [[\Yiisoft\Db\MongoDb\Query]]:

```php
use Yiisoft\Db\MongoDb\Query;

$query = new Query();
// составление запроса
$query->select(['name', 'status'])
    ->from('customer')
    ->limit(10);
// выполнение запроса
$rows = $query->all();
```

---

## File: docs/guide/ru/installation.md

Установка
============

## Требования

Это расширение требует [MongoDB PHP Extension](https://www.php.net/manual/ru/set.mongodb.php) версии 1.0.0 или выше.

## Получение с помощью Composer

Предпочтительный способ установки расширения через  [composer](https://getcomposer.org/download/).

Для этого запустите

```
composer require yiisoft/yii2-mongodb
```

или добавьте

```
"yiisoft/yii2-mongodb": "~2.1.0"
```

в секцию require вашего composer.json.

## Настройка приложения

Для использования расширения, просто добавьте этот код в конфигурацию вашего приложения:

```php
return [
    //....
    'components' => [
        'mongodb' => [
            'class' => Yiisoft\Db\MongoDb\Connection::class,
            'dsn' => 'mongodb://developer:password@localhost:27017/mydatabase',
        ],
    ],
];
```

---

## File: docs/guide/ru/topics-cache.md

Использование компонентов кеширования
=========================

Для того чтобы использованить компонент `Cache`, в дополнительных настройках соединения, как описано в разделе  [Установка](installation.md),
вы должны настроить компонент `cache` как `Yiisoft\Db\MongoDb\Cache`:

```php
return [
    //....
    'components' => [
        // ...
        'cache' => [
            'class' => Yiisoft\Db\MongoDb\Cache::class,
        ],
    ]
];
```

---

## File: docs/guide/ru/topics-debug.md

Использование MongoDB DebugPanel
============================

Расширение Yii2 MongoDB предоставляет панель отладки, которая может быть интегрирована с модулем отладки yii
и отображать выполняемые запросы MongoDB.

Добавьте следующий код в конфигурацию вашего приложения, чтобы включить его (если у вас уже есть включенный модуль отладки, то достаточно просто добавить конфигурацию панели):

```php
    // ...
    'bootstrap' => ['debug'],
    'modules' => [
        'debug' => [
            'class' => yii\debug\Module::class,
            'panels' => [
                'mongodb' => [
                    'class' => Yiisoft\Db\MongoDb\Debug\MongoDbPanel::class,
                    // 'db' => 'mongodb', // ID MongoDB компонента, по умолчанию `db`. Раскоментируйте и измените эту строку, если вы регистрируете компонент MongoDB с другим ID.
                ],
            ],
        ],
    ],
    // ...
```

---

## File: docs/guide/ru/topics-gii.md

[Binary file]

---

## File: docs/guide/ru/topics-i18n-message-source.md

Использование интернационализации I18N
=============================

Вы можете использовать [[\Yiisoft\Db\MongoDb\i18n\MongoDbMessageSource]] для хранения переводов i18n сообщений.
Пример конфигурации приложения:

```php
return [
    //....
    'components' => [
        // ...
        'i18n' => [
            'translations' => [
                '*' => [
                    'class' => Yiisoft\Db\MongoDb\i18n\MongoDbMessageSource::class
                ]
            ]
        ],
    ]
];
```

Пожалуйста, обратитесь к [[\Yiisoft\Db\MongoDb\i18n\MongoDbMessageSource]] для получения более подробной информации о конфигурации и перевода структуры коллекции данных.

---

## File: docs/guide/ru/topics-logging.md

[Binary file]

---

## File: docs/guide/ru/topics-migrations.md

Использование миграции
================

MongoDB это - schemaless-бд и может создать необходимые коллекции по первому требованию. Однако, есть много случаев когда вам может понадобиться применение постоянных изменений в базу данных MongoDB. Для примера: вам может понадобится создать коллекцию с некоторыми конкретными вариантами или индексы.
MongoDB миграции управляются с помощью [[Yiisoft\Db\MongoDb\Console\Controllers\MigrateController]], который являетя аналогом регулярного
[[\Yiisoft\Yii\Console\Controllers\MigrateController]].

Для того, чтобы включить эту команду, вы должны настроить конфигурацию консольного приложения:

```php
return [
    // ...
    'controllerMap' => [
        'mongodb-migrate' => 'Yiisoft\Db\MongoDb\Console\Controllers\MigrateController'
    ],
];
```

Ниже приведены примеры использования этой команды:

```
# создать миграцию с именем 'create_user_collection'
yii mongodb-migrate/create create_user_collection

# применить ВСЕ новые миграции
yii mongodb-migrate

# отменить последние примененные миграции
yii mongodb-migrate/down
```

---

## File: docs/guide/ru/topics-session.md

Использование компонентов сессии
===========================

Для использования компонента `Session`, в дополнительных настройках соединения, как описано в разделе [Установка](installation.md),
вы должны настроить компонент `session` как `Yiisoft\Db\MongoDb\Session`:

```php
return [
    //....
    'components' => [
        // ...
        'session' => [
            'class' => Yiisoft\Db\MongoDb\Session::class,
        ],
    ]
];
```

---

## File: docs/guide/ru/usage-ar.md

[Binary file]

---

## File: docs/guide/ru/usage-embedded-documents.md

Работа с вложенными документами
===============================

Расширение не предусматривает каких-либо специальных способов работы с вложенными документами (суб-документы) на данный момент.
Общая рекомендация избегать их, если это возможно. В качестве примера: 

Вместо:

```
{
    content: "some content",
    author: {
        name: author1,
        email: author1@domain.com
    }
}
```

используйте следующее:

```
{
    content: "some content",
    author_name: author1,
    author_email: author1@domain.com
}
```

При разработке Yii Model предполагалось, что каждый отдельный атрибут модели является скаляром. Валидация и обработка атрибутов происходит на основе этого предположения.
Тем не менее, любой атрибут может быть массивом любой глубины и сложности, однако вы должны обрабатывать его валидацию по своему усмотрению.

Пока не существует явной поддержки вложенных документов, но также никакого явного ограничения на него нет. Вы можете создать собственное решение или использовать расширение сторонних разработчиков, как [yii2tech/embedded](https://github.com/yii2tech/embedded) для использования этой функции.

---

## File: docs/guide/ru/usage-gridfs.md

Использование GridFS
============

Расширение поддерживает [MongoGridFS](https://docs.mongodb.com/manual/core/gridfs/) с помощью классов из пространства имен "\Yiisoft\Db\MongoDb\File".
Там вы найдете классы Collection, Query и ActiveRecord.

Вы можете загрузить файл с помощью [[\Yiisoft\Db\MongoDb\File\Upload]]:

```php
$document = Yii::$app->mongodb->getFileCollection()->createUpload()
    ->addContent('Part 1')
    ->addContent('Part 2')
    // ...
    ->complete();
```

Вы можете скачать файл с помощью [[\Yiisoft\Db\MongoDb\File\Download]]:

```php
Yii::$app->mongodb->getFileCollection()->createDownload($document['_id'])->toFile('/path/to/file.dat');
```

Каждая строка, файла результата запроса, содержит ключ 'file' экземпляра [[\Yiisoft\Db\MongoDb\File\Download]]:

```php
use Yiisoft\Db\MongoDb\File\Query;

$query = new Query();
$rows = $query->from('fs')
    ->limit(10)
    ->all();

foreach ($rows as $row) {
    var_dump($row['file']); // вывод: "object(\Yiisoft\Db\MongoDb\File\Download)"
    echo $row['file']->toString(); // содержание файла вывода
}
```

С помощью [\Yiisoft\Db\MongoDb\File\ActiveRecord]] вы можете манипулировать файлами используя свойство 'file':

```php
use Yiisoft\Db\MongoDb\File\ActiveRecord;

class ImageFile extends ActiveRecord
{
    //...
}

$record = new ImageFile();
$record->number = 15;
$record->file = '/path/to/some/file.jpg'; // локальная загрузка файла GridFS
$record->save();

$record = ImageFile::find()->where(['number' => 15])->one();
var_dump($record->file); // вывод: "object(\Yiisoft\Db\MongoDb\File\Download)"
echo $row['file']->toString(); // содержание файла вывода
```

Вы также можете управлять файлами GridFS через регулярные потоки ресурсов PHP.
Вам нужно будет зарегистрировать обертку потока предоставленную этим расширением - [[\Yiisoft\Db\MongoDb\File\StreamWrapper]].
Это может быть сделано с помощью [[\Yiisoft\Db\MongoDb\File\Connection::registerFileStreamWrapper()]].
После того как обертка потока зарегистрирована, вы можете открыть поток используя следующий формат:

```
'protocol://databaseName.fileCollectionPrefix?file_attribute=value'
```

Для примера:

```php
Yii::$app->mongodb->registerFileStreamWrapper(); // register stream wrapper

// запись файла:
$resource = fopen('gridfs://mydatabase.fs?filename=new_file.txt', 'w');
fwrite($resource, 'some content');
// ...
fclose($resource);

// запись файла с несколькими полями:
$resource = fopen('gridfs://mydatabase.fs?filename=new_file.txt&number=17&status=active', 'w');
fwrite($resource, 'file number 17 with status "active"');
fclose($resource);

// чтение файла:
$resource = fopen('gridfs://mydatabase.fs?filename=my_file.txt', 'r');
$fileContent = stream_get_contents($resource);
```

---

## File: docs/guide/ru/usage-mongoid.md

[Binary file]

---

## File: .github/CODE_OF_CONDUCT.md

# Yii Contributor Code of Conduct

## Our Pledge

As contributors and maintainers of this project, and in order to keep Yii community open and welcoming, we ask to respect all community members.

## Our Standards

Examples of behavior that contributes to creating a positive environment include:

* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members

Examples of unacceptable behavior by participants include:

* The use of sexualized language or imagery and unwelcome sexual attention or
  advances
* Personal attacks
* Trolling or insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing other's private information, such as physical or electronic
  addresses, without explicit permission
* Other conduct which could reasonably be considered inappropriate in
  a professional setting

## Our Responsibilities

Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in response
to any instances of unacceptable behavior.

Project maintainers have the right and responsibility to remove, edit, or reject comments,
commits, code, wiki edits, issues, and other contributions that are not aligned to this
Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors
that they deem inappropriate, threatening, offensive, or harmful.

## Scope

This Code of Conduct applies both within project spaces and in public spaces when
an individual is representing the project or its community. Examples of representing
a project or community include posting via an official social media account,
within project GitHub, official forum or acting as an appointed representative at
an online or offline event.

## Enforcement

Instances of abusive, harassing, or otherwise unacceptable behavior may be reported
by contacting core team members. All complaints will be reviewed and investigated
and will result in a response that is deemed necessary and appropriate to the circumstances.
The project team is obligated to maintain confidentiality with regard to the reporter of
an incident. Further details of specific enforcement policies may be posted separately.

Project maintainers who do not follow or enforce the Code of Conduct in good faith
may face temporary or permanent repercussions as determined by other members of
the project's leadership.

## Attribution

This Code of Conduct is adapted from the [Contributor Covenant][homepage],
version 1.4.0, available at
[https://contributor-covenant.org/version/1/4/][version]

[homepage]: https://contributor-covenant.org
[version]: https://contributor-covenant.org/version/1/4/

---

## File: .github/CONTRIBUTING.md

# Prerequisites

- [Yii goal and values](https://github.com/yiisoft/docs/blob/master/001-yii-values.md)
- [Namespaces](https://github.com/yiisoft/docs/blob/master/004-namespaces.md)
- [Git commit messages](https://github.com/yiisoft/docs/blob/master/006-git-commit-messages.md)
- [Exceptions](https://github.com/yiisoft/docs/blob/master/007-exceptions.md)
- [Interfaces](https://github.com/yiisoft/docs/blob/master/008-interfaces.md)

# Getting started

Since Yii 3 consists of many packages, we have a [special development tool](https://github.com/yiisoft/docs/blob/master/005-development-tool.md).

1. [Clone the repository](https://github.com/yiisoft/yii-dev-tool).

2. [Set up your own fork](https://github.com/yiisoft/yii-dev-tool#using-your-own-fork).

3. Now you are ready. Fork any package listed in `packages.php` and do `./yii-dev install username/package`.

If you don't have any particular package in mind to start with:

- [Check roadmap](https://github.com/yiisoft/docs/blob/master/003-roadmap.md).
- Check package issues at github. Usually there are some.
- Ask @samdark.

---

## File: .github/dependabot.yml

version: 2
updates:
    # Maintain dependencies for GitHub Actions
    - package-ecosystem: "github-actions"
      directory: "/"
      schedule:
          interval: "daily"

    # Maintain dependencies for Composer
    - package-ecosystem: "composer"
      directory: "/"
      schedule:
          interval: "daily"
      versioning-strategy: increase-if-necessary

---

## File: .github/FUNDING.yml

# These are supported funding model platforms

open_collective: yiisoft
github: [yiisoft]

---

## File: .github/ISSUE_TEMPLATE.md

### What steps will reproduce the problem?

### What is the expected result?

### What do you get instead?


### Additional info

| Q                | A
| ---------------- | ---
| Version          | 1.0.?
| PHP version      | 
| Operating system |

---

## File: .github/PULL_REQUEST_TEMPLATE.md

| Q             | A
| ------------- | ---
| Is bugfix?    | ✔️/❌
| New feature?  | ✔️/❌
| Breaks BC?    | ✔️/❌
| Fixed issues  | comma-separated list of tickets # fixed by the PR, if any

---

## File: .github/SECURITY.md

# Security Policy

Please use the [security issue form](https://www.yiiframework.com/security) to report to us any security issue you
find in Yii. DO NOT use the issue tracker or discuss it in the public forum as it will cause more damage than help.

Please note that as a non-commercial OpenSource project we are not able to pay bounties at the moment.

---

## File: .github/workflows/rector-cs.yml

name: Rector + PHP CS Fixer

on:
  pull_request_target:
    paths:
      - 'src/**'
      - '.github/workflows/rector-cs.yml'
      - 'composer.json'
      - 'rector.php'
      - '.php-cs-fixer.dist.php'

permissions:
  contents: read

concurrency:
  group: ${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: true

jobs:
  rector:
    uses: yiisoft/actions/.github/workflows/rector-cs.yml@master
    secrets:
      token: ${{ secrets.YIISOFT_GITHUB_TOKEN }}
    with:
      php: '8.1'