# Class yii\mongodb\QueryBuilder

Inheritance | yii\mongodb\QueryBuilder » yii\base\BaseObject
Implements | yii\base\Configurable
Available since version | 2.1
Source Code | https://github.com/yiisoft/yii2-mongodb/blob/master/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
--- | --- | ---
__call() | Calls the named method which is not a class method. | yii\base\BaseObject
__construct() | Constructor. | yii\mongodb\QueryBuilder
__get() | Returns the value of an object property. | yii\base\BaseObject
__isset() | Checks if a property is set, i.e. defined and not null. | yii\base\BaseObject
__set() | Sets value of an object property. | yii\base\BaseObject
__unset() | Sets an object property to null. | yii\base\BaseObject
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
canGetProperty() | Returns a value indicating whether a property can be read. | yii\base\BaseObject
canSetProperty() | Returns a value indicating whether a property can be set. | yii\base\BaseObject
className() | Returns the fully qualified name of this class. | yii\base\BaseObject
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() |  | yii\mongodb\QueryBuilder
hasMethod() | Returns a value indicating whether a method is defined. | yii\base\BaseObject
hasProperty() | Returns a value indicating whether a property is defined. | yii\base\BaseObject
init() | Initializes the object. | yii\base\BaseObject
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

$db public property

The MongoDB connection.

public yii\mongodb\Connection $db = null

## Method Details

__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

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.

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.

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.

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 yii\mongodb\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

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.

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.

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.

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.

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.

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.

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.

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.

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.

count() public method

Generates count command

public array count ( $collectionName, $condition = [], $options = [] )
$collectionName | string |
$condition | array |
$options | array |
return | array | Command document.

createCollection() public method

Generates 'create collection' command.

https://docs.mongodb.com/manual/reference/method/db.createCollection/

public array createCollection ( $collectionName, array $options = [] )
$collectionName | string | Collection name.
$options | array | Collection options in format: "name" => "value"
return | array | Command document.

createIndexes() public method

Generates create indexes command.

See also https://docs.mongodb.com/manual/reference/method/db.collection.createIndex/.

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.

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.

dropCollection() public method

Generates drop collection command.

https://docs.mongodb.com/manual/reference/method/db.collection.drop/

public array dropCollection ( $collectionName )
$collectionName | string | Name of the collection to be dropped.
return | array | Command document.

dropDatabase() public method

Generates drop database command.

https://docs.mongodb.com/manual/reference/method/db.dropDatabase/

public array dropDatabase ( )
return | array | Command document.

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.

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).

explain() public method

Generates 'explain' command.

public array explain ( $collectionName, $query )
$collectionName | string | Collection name.
$query | array | Query options.
return | array | Command document.

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.

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.

group() public method

public void group ( $collectionName, $keys, $initial, $reduce, $options = [] )
$collectionName |  |
$keys |  |
$initial |  |
$reduce |  |
$options |  |

listCollections() public method

Generates 'listCollections' command.

public array listCollections ( $condition = [], $options = [] )
$condition | array | Filter condition.
$options | array | Command options.
return | array | Command document.

listDatabases() public method

Generates 'listDatabases' command.

public array listDatabases ( $condition = [], $options = [] )
$condition | array | Filter condition.
$options | array | Command options.
return | array | Command 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.

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.

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.