Class yii\mongodb\QueryBuilder

Inheritanceyii\mongodb\QueryBuilder » yii\base\BaseObject
Available since extension's version2.1
Source Code https://github.com/yiisoft/yii2-mongodb/blob/master/src/QueryBuilder.php

QueryBuilder builds a MongoDB command statements.

It is used by yii\mongodb\Command for particular commands and queries composition.

MongoDB uses JSON format to specify query conditions with quite specific syntax. However buildCondition() method provides the ability of "translating" common condition format used "yii\db*" into MongoDB condition. For example:

$condition = [
    [
        'OR',
        ['AND', ['first_name' => 'John'], ['last_name' => 'Smith']],
        ['status' => [1, 2, 3]]
    ],
];
print_r(Yii::$app->mongodb->getQueryBuilder()->buildCondition($condition));
// outputs :
[
    '$or' => [
        [
            'first_name' => 'John',
            'last_name' => 'John',
        ],
        [
            'status' => ['$in' => [1, 2, 3]],
        ]
    ]
]

Note: condition values for the key '_id' will be automatically cast to \MongoDB\BSON\ObjectID instance, even if they are plain strings. However, if you have other columns, containing \MongoDB\BSON\ObjectID, you should take care of possible typecast on your own.

Public Properties

Hide inherited properties

Property Type Description Defined By
$db yii\mongodb\Connection The MongoDB connection. yii\mongodb\QueryBuilder

Public Methods

Hide inherited methods

Method Description Defined By
__construct() Constructor. yii\mongodb\QueryBuilder
aggregate() Generates 'aggregate' command. yii\mongodb\QueryBuilder
buildAndCondition() Connects two or more conditions with the AND operator. yii\mongodb\QueryBuilder
buildBetweenCondition() Creates an Mongo condition, which emulates the BETWEEN operator. yii\mongodb\QueryBuilder
buildCondition() Parses the condition specification and generates the corresponding Mongo condition. yii\mongodb\QueryBuilder
buildHashCondition() Creates a condition based on column-value pairs. yii\mongodb\QueryBuilder
buildInCondition() Creates an Mongo condition with the IN operator. yii\mongodb\QueryBuilder
buildLikeCondition() Creates a Mongo condition, which emulates the LIKE operator. yii\mongodb\QueryBuilder
buildNotCondition() Composes NOT condition. yii\mongodb\QueryBuilder
buildOrCondition() Connects two or more conditions with the OR operator. yii\mongodb\QueryBuilder
buildRegexCondition() Creates a Mongo regular expression condition. yii\mongodb\QueryBuilder
buildSelectFields() Normalizes fields list for the MongoDB select composition. yii\mongodb\QueryBuilder
buildSimpleCondition() Creates an Mongo condition like {$operator:{field:value}}. yii\mongodb\QueryBuilder
buildSortFields() Normalizes fields list for the MongoDB sort composition. yii\mongodb\QueryBuilder
count() Generates count command yii\mongodb\QueryBuilder
createCollection() Generates 'create collection' command. yii\mongodb\QueryBuilder
createIndexes() Generates create indexes command. yii\mongodb\QueryBuilder
distinct() Generates 'distinct' command. yii\mongodb\QueryBuilder
dropCollection() Generates drop collection command. yii\mongodb\QueryBuilder
dropDatabase() Generates drop database command. yii\mongodb\QueryBuilder
dropIndexes() Generates drop indexes command. yii\mongodb\QueryBuilder
explain() Generates 'explain' command. yii\mongodb\QueryBuilder
findAndModify() Generates 'find and modify' command. yii\mongodb\QueryBuilder
generateIndexName() Generates index name for the given column orders. yii\mongodb\QueryBuilder
group() Generates 'group' command. yii\mongodb\QueryBuilder
listCollections() Generates 'listCollections' command. yii\mongodb\QueryBuilder
listDatabases() Generates 'listDatabases' command. yii\mongodb\QueryBuilder
listIndexes() Generates list indexes command. yii\mongodb\QueryBuilder
mapReduce() Generates 'map-reduce' command. yii\mongodb\QueryBuilder

Protected Methods

Hide inherited methods

Method Description Defined By
ensureMongoId() Converts given value into ObjectID instance. yii\mongodb\QueryBuilder
normalizeConditionKeyword() Converts "\yii\db*" quick condition keyword into actual Mongo condition keyword. yii\mongodb\QueryBuilder

Property Details

Hide inherited properties

$db public property

The MongoDB connection.

Method Details

Hide inherited methods

__construct() public method

Constructor.

public void __construct ( $connection, $config = [] )
$connection yii\mongodb\Connection

The database connection.

$config array

Name-value pairs that will be used to initialize the object properties

                public function __construct($connection, $config = [])
{
    $this->db = $connection;
    parent::__construct($config);
}

            
aggregate() public method

Generates 'aggregate' command.

public array aggregate ( $collectionName, $pipelines, $options = [] )
$collectionName string

Collection name

$pipelines array

List of pipeline operators.

$options array

Optional parameters.

return array

Command document.

                public function aggregate($collectionName, $pipelines, $options = [])
{
    foreach ($pipelines as $key => $pipeline) {
        if (isset($pipeline['$match'])) {
            $pipelines[$key]['$match'] = $this->buildCondition($pipeline['$match']);
        }
    }
    $document = array_merge(
        [
            'aggregate' => $collectionName,
            'pipeline' => $pipelines,
            'allowDiskUse' => false,
        ],
        $options
    );
    return $document;
}

            
buildAndCondition() public method

Connects two or more conditions with the AND operator.

public array buildAndCondition ( $operator, $operands )
$operator string

The operator to use for connecting the given operands

$operands array

The Mongo conditions to connect.

return array

The generated Mongo condition.

                public function buildAndCondition($operator, $operands)
{
    $operator = $this->normalizeConditionKeyword($operator);
    $parts = [];
    foreach ($operands as $operand) {
        $parts[] = $this->buildCondition($operand);
    }
    return [$operator => $parts];
}

            
buildBetweenCondition() public method

Creates an Mongo condition, which emulates the BETWEEN operator.

public array buildBetweenCondition ( $operator, $operands )
$operator string

The operator to use

$operands array

The first operand is the column name. The second and third operands describe the interval that column value should be in.

return array

The generated Mongo condition.

throws \yii\base\InvalidParamException

if wrong number of operands have been given.

                public function buildBetweenCondition($operator, $operands)
{
    if (!isset($operands[0], $operands[1], $operands[2])) {
        throw new InvalidParamException("Operator '$operator' requires three operands.");
    }
    list($column, $value1, $value2) = $operands;
    if (strncmp('NOT', $operator, 3) === 0) {
        return [
            $column => [
                '$lt' => $value1,
                '$gt' => $value2,
            ]
        ];
    }
    return [
        $column => [
            '$gte' => $value1,
            '$lte' => $value2,
        ]
    ];
}

            
buildCondition() public method

Parses the condition specification and generates the corresponding Mongo condition.

public array buildCondition ( $condition )
$condition array

The condition specification. Please refer to Query::where() on how to specify a condition.

return array

The generated Mongo condition

throws \yii\base\InvalidParamException

if the condition is in bad format

                public function buildCondition($condition)
{
    static $builders = [
        'NOT' => 'buildNotCondition',
        'AND' => 'buildAndCondition',
        'OR' => 'buildOrCondition',
        'BETWEEN' => 'buildBetweenCondition',
        'NOT BETWEEN' => 'buildBetweenCondition',
        'IN' => 'buildInCondition',
        'NOT IN' => 'buildInCondition',
        'REGEX' => 'buildRegexCondition',
        'LIKE' => 'buildLikeCondition',
    ];
    if (!is_array($condition)) {
        throw new InvalidParamException('Condition should be an array.');
    } elseif (empty($condition)) {
        return [];
    }
    if (isset($condition[0])) { // operator format: operator, operand 1, operand 2, ...
        $operator = strtoupper($condition[0]);
        if (isset($builders[$operator])) {
            $method = $builders[$operator];
        } else {
            $operator = $condition[0];
            $method = 'buildSimpleCondition';
        }
        array_shift($condition);
        return $this->$method($operator, $condition);
    }
    // hash format: 'column1' => 'value1', 'column2' => 'value2', ...
    return $this->buildHashCondition($condition);
}

            
buildHashCondition() public method

Creates a condition based on column-value pairs.

public array buildHashCondition ( $condition )
$condition array

The condition specification.

return array

The generated Mongo condition.

                public function buildHashCondition($condition)
{
    $result = [];
    foreach ($condition as $name => $value) {
        if (strncmp('$', $name, 1) === 0) {
            // Native Mongo condition:
            $result[$name] = $value;
        } else {
            if (is_array($value)) {
                if (ArrayHelper::isIndexed($value)) {
                    // Quick IN condition:
                    $result = array_merge($result, $this->buildInCondition('IN', [$name, $value]));
                } else {
                    // Mongo complex condition:
                    $result[$name] = $value;
                }
            } else {
                // Direct match:
                if ($name == '_id') {
                    $value = $this->ensureMongoId($value);
                }
                $result[$name] = $value;
            }
        }
    }
    return $result;
}

            
buildInCondition() public method

Creates an Mongo condition with the IN operator.

public array buildInCondition ( $operator, $operands )
$operator string

The operator to use (e.g. IN or NOT IN)

$operands array

The first operand is the column name. If it is an array a composite IN condition will be generated. The second operand is an array of values that column value should be among.

return array

The generated Mongo condition.

throws \yii\base\InvalidParamException

if wrong number of operands have been given.

                public function buildInCondition($operator, $operands)
{
    if (!isset($operands[0], $operands[1])) {
        throw new InvalidParamException("Operator '$operator' requires two operands.");
    }
    list($column, $values) = $operands;
    $values = (array) $values;
    $operator = $this->normalizeConditionKeyword($operator);
    if (!is_array($column)) {
        $columns = [$column];
        $values = [$column => $values];
    } elseif (count($column) > 1) {
        return $this->buildCompositeInCondition($operator, $column, $values);
    } else {
        $columns = $column;
        $values = [$column[0] => $values];
    }
    $result = [];
    foreach ($columns as $column) {
        if ($column == '_id') {
            $inValues = $this->ensureMongoId($values[$column]);
        } else {
            $inValues = $values[$column];
        }
        $inValues = array_values($inValues);
        if (count($inValues) === 1 && $operator === '$in') {
            $result[$column] = $inValues[0];
        } else {
            $result[$column][$operator] = $inValues;
        }
    }
    return $result;
}

            
buildLikeCondition() public method

Creates a Mongo condition, which emulates the LIKE operator.

public array buildLikeCondition ( $operator, $operands )
$operator string

The operator to use

$operands array

The first operand is the column name. The second operand is a single value that column value should be compared with.

return array

The generated Mongo condition.

throws \yii\base\InvalidParamException

if wrong number of operands have been given.

                public function buildLikeCondition($operator, $operands)
{
    if (!isset($operands[0], $operands[1])) {
        throw new InvalidParamException("Operator '$operator' requires two operands.");
    }
    list($column, $value) = $operands;
    if (!($value instanceof Regex)) {
        $value = new Regex(preg_quote($value), 'i');
    }
    return [$column => $value];
}

            
buildNotCondition() public method

Composes NOT condition.

public array buildNotCondition ( $operator, $operands )
$operator string

The operator to use for connecting the given operands

$operands array

The Mongo conditions to connect.

return array

The generated Mongo condition.

throws \yii\base\InvalidParamException

if wrong number of operands have been given.

                public function buildNotCondition($operator, $operands)
{
    if (count($operands) !== 2) {
        throw new InvalidParamException("Operator '$operator' requires two operands.");
    }
    list($name, $value) = $operands;
    $result = [];
    if (is_array($value)) {
        $result[$name] = ['$not' => $this->buildCondition($value)];
    } else {
        if ($name == '_id') {
            $value = $this->ensureMongoId($value);
        }
        $result[$name] = ['$ne' => $value];
    }
    return $result;
}

            
buildOrCondition() public method

Connects two or more conditions with the OR operator.

public array buildOrCondition ( $operator, $operands )
$operator string

The operator to use for connecting the given operands

$operands array

The Mongo conditions to connect.

return array

The generated Mongo condition.

                public function buildOrCondition($operator, $operands)
{
    $operator = $this->normalizeConditionKeyword($operator);
    $parts = [];
    foreach ($operands as $operand) {
        $parts[] = $this->buildCondition($operand);
    }
    return [$operator => $parts];
}

            
buildRegexCondition() public method

Creates a Mongo regular expression condition.

public array buildRegexCondition ( $operator, $operands )
$operator string

The operator to use

$operands array

The first operand is the column name. The second operand is a single value that column value should be compared with.

return array

The generated Mongo condition.

throws \yii\base\InvalidParamException

if wrong number of operands have been given.

                public function buildRegexCondition($operator, $operands)
{
    if (!isset($operands[0], $operands[1])) {
        throw new InvalidParamException("Operator '$operator' requires two operands.");
    }
    list($column, $value) = $operands;
    if (!($value instanceof Regex)) {
        if (preg_match('~\/(.+)\/(.*)~', $value, $matches)) {
            $value = new Regex($matches[1], $matches[2]);
        } else {
            $value = new Regex($value, '');
        }
    }
    return [$column => $value];
}

            
buildSelectFields() public method

Normalizes fields list for the MongoDB select composition.

public array buildSelectFields ( $fields )
$fields array|string

Raw fields.

return array

Normalized select fields.

                public function buildSelectFields($fields)
{
    $selectFields = [];
    foreach ((array)$fields as $key => $value) {
        if (is_int($key)) {
            $selectFields[$value] = true;
        } else {
            $selectFields[$key] = is_scalar($value) ? (bool)$value : $value;
        }
    }
    return $selectFields;
}

            
buildSimpleCondition() public method

Creates an Mongo condition like {$operator:{field:value}}.

public string buildSimpleCondition ( $operator, $operands )
$operator string

The operator to use. Besides regular MongoDB operators, aliases like >, <=, and so on, can be used here.

$operands array

The first operand is the column name. The second operand is a single value that column value should be compared with.

return string

The generated Mongo condition.

throws \yii\base\InvalidParamException

if wrong number of operands have been given.

                public function buildSimpleCondition($operator, $operands)
{
    if (count($operands) !== 2) {
        throw new InvalidParamException("Operator '$operator' requires two operands.");
    }
    list($column, $value) = $operands;
    if (strncmp('$', $operator, 1) !== 0) {
        static $operatorMap = [
            '>' => '$gt',
            '<' => '$lt',
            '>=' => '$gte',
            '<=' => '$lte',
            '!=' => '$ne',
            '<>' => '$ne',
            '=' => '$eq',
            '==' => '$eq',
        ];
        if (isset($operatorMap[$operator])) {
            $operator = $operatorMap[$operator];
        } else {
            throw new InvalidParamException("Unsupported operator '{$operator}'");
        }
    }
    return [$column => [$operator => $value]];
}

            
buildSortFields() public method

Normalizes fields list for the MongoDB sort composition.

public array buildSortFields ( $fields )
$fields array|string

Raw fields.

return array

Normalized sort fields.

                public function buildSortFields($fields)
{
    $sortFields = [];
    foreach ((array)$fields as $key => $value) {
        if (is_int($key)) {
            $sortFields[$value] = +1;
        } else {
            if ($value === SORT_ASC) {
                $value = +1;
            } elseif ($value === SORT_DESC) {
                $value = -1;
            }
            $sortFields[$key] = $value;
        }
    }
    return $sortFields;
}

            
count() public method

Generates count command

public array count ( $collectionName, $condition = [], $options = [] )
$collectionName string
$condition array
$options array
return array

Command document.

                public function count($collectionName, $condition = [], $options = [])
{
    $document = ['count' => $collectionName];
    if (!empty($condition)) {
        $document['query'] = (object) $this->buildCondition($condition);
    }
    return array_merge($document, $options);
}

            
createCollection() public method
public array createCollection ( $collectionName, array $options = [] )
$collectionName string

Collection name.

$options array

Collection options in format: "name" => "value"

return array

Command document.

                public function createCollection($collectionName, array $options = [])
{
    $document = array_merge(['create' => $collectionName], $options);
    if (isset($document['indexOptionDefaults'])) {
        $document['indexOptionDefaults'] = (object) $document['indexOptionDefaults'];
    }
    if (isset($document['storageEngine'])) {
        $document['storageEngine'] = (object) $document['storageEngine'];
    }
    if (isset($document['validator'])) {
        $document['validator'] = (object) $document['validator'];
    }
    return $document;
}

            
createIndexes() public method
public array createIndexes ( $databaseName, $collectionName, $indexes )
$databaseName string|null

Database name.

$collectionName string

Collection name.

$indexes array[]

Indexes specification. Each specification should be an array in format: optionName => value The main options are:

  • keys: array, column names with sort order, to be indexed. This option is mandatory.
  • unique: bool, whether to create unique index.
  • name: string, the name of the index, if not set it will be generated automatically.
  • background: bool, whether to bind index in the background.
  • sparse: bool, whether index should reference only documents with the specified field.

See [[https://docs.mongodb.com/manual/reference/method/db.collection.createIndex/#options-for-all-index-types]] for the full list of options.

return array

Command document.

                public function createIndexes($databaseName, $collectionName, $indexes)
{
    $normalizedIndexes = [];
    foreach ($indexes as $index) {
        if (!isset($index['key'])) {
            throw new InvalidParamException('"key" is required for index specification');
        }
        $index['key'] = $this->buildSortFields($index['key']);
        if (!isset($index['ns'])) {
            if ($databaseName === null) {
                $databaseName = $this->db->getDefaultDatabaseName();
            }
            $index['ns'] = $databaseName . '.' . $collectionName;
        }
        if (!isset($index['name'])) {
            $index['name'] = $this->generateIndexName($index['key']);
        }
        $normalizedIndexes[] = $index;
    }
    return [
        'createIndexes' => $collectionName,
        'indexes' => $normalizedIndexes,
    ];
}

            
distinct() public method

Generates 'distinct' command.

public array distinct ( $collectionName, $fieldName, $condition = [], $options = [] )
$collectionName string

Collection name.

$fieldName string

Target field name.

$condition array

Filter condition

$options array

List of options in format: optionName => optionValue.

return array

Command document.

                public function distinct($collectionName, $fieldName, $condition = [], $options = [])
{
    $document = array_merge(
        [
            'distinct' => $collectionName,
            'key' => $fieldName,
        ],
        $options
    );
    if (!empty($condition)) {
        $document['query'] = $this->buildCondition($condition);
    }
    return $document;
}

            
dropCollection() public method
public array dropCollection ( $collectionName )
$collectionName string

Name of the collection to be dropped.

return array

Command document.

                public function dropCollection($collectionName)
{
    return ['drop' => $collectionName];
}

            
dropDatabase() public method
public array dropDatabase ( )
return array

Command document.

                public function dropDatabase()
{
    return ['dropDatabase' => 1];
}

            
dropIndexes() public method

Generates drop indexes command.

public array dropIndexes ( $collectionName, $index )
$collectionName string

Collection name

$index string

Index name or pattern, use * in order to drop all indexes.

return array

Command document.

                public function dropIndexes($collectionName, $index)
{
    return [
        'dropIndexes' => $collectionName,
        'index' => $index,
    ];
}

            
ensureMongoId() protected method

Converts given value into ObjectID instance.

If array given, each element of it will be processed.

protected array|\MongoDB\BSON\ObjectID ensureMongoId ( $rawId )
$rawId mixed

Raw id(s).

return array|\MongoDB\BSON\ObjectID

Normalized id(s).

                protected function ensureMongoId($rawId)
{
    if (is_array($rawId)) {
        $result = [];
        foreach ($rawId as $key => $value) {
            $result[$key] = $this->ensureMongoId($value);
        }
        return $result;
    } elseif (is_object($rawId)) {
        if ($rawId instanceof ObjectID) {
            return $rawId;
        } else {
            $rawId = (string) $rawId;
        }
    }
    try {
        $mongoId = new ObjectID($rawId);
    } catch (InvalidArgumentException $e) {
        // invalid id format
        $mongoId = $rawId;
    }
    return $mongoId;
}

            
explain() public method

Generates 'explain' command.

public array explain ( $collectionName, $query )
$collectionName string

Collection name.

$query array

Query options.

return array

Command document.

                public function explain($collectionName, $query)
{
    $query = array_merge(
        ['find' => $collectionName],
        $query
    );
    if (isset($query['filter'])) {
        $query['filter'] = (object) $this->buildCondition($query['filter']);
    }
    if (isset($query['projection'])) {
        $query['projection'] = $this->buildSelectFields($query['projection']);
    }
    if (isset($query['sort'])) {
        $query['sort'] = $this->buildSortFields($query['sort']);
    }
    return [
        'explain' => $query,
    ];
}

            
findAndModify() public method

Generates 'find and modify' command.

public array findAndModify ( $collectionName, $condition = [], $update = [], $options = [] )
$collectionName string

Collection name

$condition array

Filter condition

$update array

Update criteria

$options array

List of options in format: optionName => optionValue.

return array

Command document.

                public function findAndModify($collectionName, $condition = [], $update = [], $options = [])
{
    $document = array_merge(['findAndModify' => $collectionName], $options);
    if (!empty($condition)) {
        $options['query'] = $this->buildCondition($condition);
    }
    if (!empty($update)) {
        $options['update'] = $update;
    }
    if (isset($options['fields'])) {
        $options['fields'] = $this->buildSelectFields($options['fields']);
    }
    if (isset($options['sort'])) {
        $options['sort'] = $this->buildSortFields($options['sort']);
    }
    foreach (['fields', 'query', 'sort', 'update'] as $name) {
        if (isset($options[$name])) {
            $document[$name] = (object) $options[$name];
        }
    }
    return $document;
}

            
generateIndexName() public method

Generates index name for the given column orders.

Columns should be normalized using buildSortFields() before being passed to this method.

public string generateIndexName ( $columns )
$columns array

Columns with sort order.

return string

Index name.

                public function generateIndexName($columns)
{
    $parts = [];
    foreach ($columns as $column => $order) {
        $parts[] = $column . '_' . $order;
    }
    return implode('_', $parts);
}

            
group() public method

Generates 'group' command.

public array group ( $collectionName, $keys, $initial, $reduce, $options = [] )
$collectionName string
$keys mixed

Fields to group by. If an array or non-code object is passed, it will be the key used to group results. If instance of Javascript passed, it will be treated as a function that returns the key to group by.

$initial array

Initial value of the aggregation counter object.

$reduce \MongoDB\BSON\Javascript|string

Function that takes two arguments (the current document and the aggregation to this point) and does the aggregation. Argument will be automatically cast to Javascript.

$options array

Optional parameters to the group command. Valid options include:

  • condition - criteria for including a document in the aggregation.
  • finalize - function called once per unique key that takes the final output of the reduce function.
return array

Command document.

                public function group($collectionName, $keys, $initial, $reduce, $options = [])
{
    if (!($reduce instanceof Javascript)) {
        $reduce = new Javascript((string) $reduce);
    }
    if (isset($options['condition'])) {
        $options['cond'] = $this->buildCondition($options['condition']);
        unset($options['condition']);
    }
    if (isset($options['finalize'])) {
        if (!($options['finalize'] instanceof Javascript)) {
            $options['finalize'] = new Javascript((string) $options['finalize']);
        }
    }
    if (isset($options['keyf'])) {
        $options['$keyf'] = $options['keyf'];
        unset($options['keyf']);
    }
    if (isset($options['$keyf'])) {
        if (!($options['$keyf'] instanceof Javascript)) {
            $options['$keyf'] = new Javascript((string) $options['$keyf']);
        }
    }
    $document = [
        'group' => array_merge(
            [
                'ns' => $collectionName,
                'key' => $keys,
                'initial' => $initial,
                '$reduce' => $reduce,
            ],
            $options
        )
    ];
    return $document;
}

            
listCollections() public method

Generates 'listCollections' command.

public array listCollections ( $condition = [], $options = [] )
$condition array

Filter condition.

$options array

Command options.

return array

Command document.

                public function listCollections($condition = [], $options = [])
{
    $document = array_merge(['listCollections' => 1], $options);
    if (!empty($condition)) {
        $document['filter'] = (object)$this->buildCondition($condition);
    }
    return $document;
}

            
listDatabases() public method

Generates 'listDatabases' command.

public array listDatabases ( $condition = [], $options = [] )
$condition array

Filter condition.

$options array

Command options.

return array

Command document.

                public function listDatabases($condition = [], $options = [])
{
    $document = array_merge(['listDatabases' => 1], $options);
    if (!empty($condition)) {
        $document['filter'] = (object)$this->buildCondition($condition);
    }
    return $document;
}

            
listIndexes() public method

Generates list indexes command.

public array listIndexes ( $collectionName, $options = [] )
$collectionName string

Collection name

$options array

Command options. Available options are:

  • maxTimeMS: int, max execution time in ms.
return array

Command document.

                public function listIndexes($collectionName, $options = [])
{
    return array_merge(['listIndexes' => $collectionName], $options);
}

            
mapReduce() public method

Generates 'map-reduce' command.

See also https://docs.mongodb.com/manual/core/map-reduce/.

public array mapReduce ( $collectionName, $map, $reduce, $out, $condition = [], $options = [] )
$collectionName string

Collection name.

$map \MongoDB\BSON\Javascript|string

Function, which emits map data from collection. Argument will be automatically cast to \MongoDB\BSON\Javascript.

$reduce \MongoDB\BSON\Javascript|string

Function that takes two arguments (the map key and the map values) and does the aggregation. Argument will be automatically cast to \MongoDB\BSON\Javascript.

$out string|array

Output collection name. It could be a string for simple output ('outputCollection'), or an array for parametrized output (['merge' => 'outputCollection']). You can pass ['inline' => true] to fetch the result at once without temporary collection usage.

$condition array

Filter condition for including a document in the aggregation.

$options array

Additional optional parameters to the mapReduce command. Valid options include:

  • sort: array, key to sort the input documents. The sort key must be in an existing index for this collection.
  • limit: int, the maximum number of documents to return in the collection.
  • finalize: \MongoDB\BSON\Javascript|string, function, which follows the reduce method and modifies the output.
  • scope: array, specifies global variables that are accessible in the map, reduce and finalize functions.
  • jsMode: bool, specifies whether to convert intermediate data into BSON format between the execution of the map and reduce functions.
  • verbose: bool, specifies whether to include the timing information in the result information.
return array

Command document.

                public function mapReduce($collectionName, $map, $reduce, $out, $condition = [], $options = [])
{
    if (!($map instanceof Javascript)) {
        $map = new Javascript((string) $map);
    }
    if (!($reduce instanceof Javascript)) {
        $reduce = new Javascript((string) $reduce);
    }
    $document = [
        'mapReduce' => $collectionName,
        'map' => $map,
        'reduce' => $reduce,
        'out' => $out
    ];
    if (!empty($condition)) {
        $document['query'] = $this->buildCondition($condition);
    }
    if (!empty($options)) {
        $document = array_merge($document, $options);
    }
    return $document;
}

            
normalizeConditionKeyword() protected method

Converts "\yii\db*" quick condition keyword into actual Mongo condition keyword.

protected string normalizeConditionKeyword ( $key )
$key string

Raw condition key.

return string

Actual key.

                protected function normalizeConditionKeyword($key)
{
    static $map = [
        'AND' => '$and',
        'OR' => '$or',
        'IN' => '$in',
        'NOT IN' => '$nin',
    ];
    $matchKey = strtoupper($key);
    if (array_key_exists($matchKey, $map)) {
        return $map[$matchKey];
    }
    return $key;
}