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
Property | Type | Description | Defined By |
---|---|---|---|
$db | yii\mongodb\Connection | The MongoDB connection. | yii\mongodb\QueryBuilder |
Public 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() | Generates 'group' command. | 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
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
Method Details
Defined in: yii\base\BaseObject::__call()
Calls the named method which is not a class method.
Do not call this method directly as it is a PHP magic method that will be implicitly called when an unknown method is being invoked.
public mixed __call ( $name, $params ) | ||
$name | string |
The method name |
$params | array |
Method parameters |
return | mixed |
The method return value |
---|---|---|
throws | yii\base\UnknownMethodException |
when calling unknown method |
public function __call($name, $params)
{
throw new UnknownMethodException('Calling unknown method: ' . get_class($this) . "::$name()");
}
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);
}
Defined in: yii\base\BaseObject::__get()
Returns the value of an object property.
Do not call this method directly as it is a PHP magic method that
will be implicitly called when executing $value = $object->property;
.
See also __set().
public mixed __get ( $name ) | ||
$name | string |
The property name |
return | mixed |
The property value |
---|---|---|
throws | yii\base\UnknownPropertyException |
if the property is not defined |
throws | yii\base\InvalidCallException |
if the property is write-only |
public function __get($name)
{
$getter = 'get' . $name;
if (method_exists($this, $getter)) {
return $this->$getter();
} elseif (method_exists($this, 'set' . $name)) {
throw new InvalidCallException('Getting write-only property: ' . get_class($this) . '::' . $name);
}
throw new UnknownPropertyException('Getting unknown property: ' . get_class($this) . '::' . $name);
}
Defined in: yii\base\BaseObject::__isset()
Checks if a property is set, i.e. defined and not null.
Do not call this method directly as it is a PHP magic method that
will be implicitly called when executing isset($object->property)
.
Note that if the property is not defined, false will be returned.
public boolean __isset ( $name ) | ||
$name | string |
The property name or the event name |
return | boolean |
Whether the named property is set (not null). |
---|
public function __isset($name)
{
$getter = 'get' . $name;
if (method_exists($this, $getter)) {
return $this->$getter() !== null;
}
return false;
}
Defined in: yii\base\BaseObject::__set()
Sets value of an object property.
Do not call this method directly as it is a PHP magic method that
will be implicitly called when executing $object->property = $value;
.
See also __get().
public void __set ( $name, $value ) | ||
$name | string |
The property name or the event name |
$value | mixed |
The property value |
throws | yii\base\UnknownPropertyException |
if the property is not defined |
---|---|---|
throws | yii\base\InvalidCallException |
if the property is read-only |
public function __set($name, $value)
{
$setter = 'set' . $name;
if (method_exists($this, $setter)) {
$this->$setter($value);
} elseif (method_exists($this, 'get' . $name)) {
throw new InvalidCallException('Setting read-only property: ' . get_class($this) . '::' . $name);
} else {
throw new UnknownPropertyException('Setting unknown property: ' . get_class($this) . '::' . $name);
}
}
Defined in: yii\base\BaseObject::__unset()
Sets an object property to null.
Do not call this method directly as it is a PHP magic method that
will be implicitly called when executing unset($object->property)
.
Note that if the property is not defined, this method will do nothing. If the property is read-only, it will throw an exception.
public void __unset ( $name ) | ||
$name | string |
The property name |
throws | yii\base\InvalidCallException |
if the property is read only. |
---|
public function __unset($name)
{
$setter = 'set' . $name;
if (method_exists($this, $setter)) {
$this->$setter(null);
} elseif (method_exists($this, 'get' . $name)) {
throw new InvalidCallException('Unsetting read-only property: ' . get_class($this) . '::' . $name);
}
}
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;
}
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];
}
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,
]
];
}
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 |
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);
}
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;
}
Creates an Mongo condition with the IN
operator.
public array buildInCondition ( $operator, $operands ) | ||
$operator | string |
The operator to use (e.g. |
$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;
}
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];
}
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;
}
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];
}
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];
}
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;
}
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 |
$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]];
}
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;
}
Defined in: yii\base\BaseObject::canGetProperty()
Returns a value indicating whether a property can be read.
A property is readable if:
- the class has a getter method associated with the specified name (in this case, property name is case-insensitive);
- the class has a member variable with the specified name (when
$checkVars
is true);
See also canSetProperty().
public boolean canGetProperty ( $name, $checkVars = true ) | ||
$name | string |
The property name |
$checkVars | boolean |
Whether to treat member variables as properties |
return | boolean |
Whether the property can be read |
---|
public function canGetProperty($name, $checkVars = true)
{
return method_exists($this, 'get' . $name) || $checkVars && property_exists($this, $name);
}
Defined in: yii\base\BaseObject::canSetProperty()
Returns a value indicating whether a property can be set.
A property is writable if:
- the class has a setter method associated with the specified name (in this case, property name is case-insensitive);
- the class has a member variable with the specified name (when
$checkVars
is true);
See also canGetProperty().
public boolean canSetProperty ( $name, $checkVars = true ) | ||
$name | string |
The property name |
$checkVars | boolean |
Whether to treat member variables as properties |
return | boolean |
Whether the property can be written |
---|
public function canSetProperty($name, $checkVars = true)
{
return method_exists($this, 'set' . $name) || $checkVars && property_exists($this, $name);
}
::class
instead.
Defined in: yii\base\BaseObject::className()
Returns the fully qualified name of this class.
public static string className ( ) | ||
return | string |
The fully qualified name of this class. |
---|
public static function className()
{
return get_called_class();
}
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);
}
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. |
---|
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;
}
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:
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,
];
}
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;
}
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. |
---|
public function dropCollection($collectionName)
{
return ['drop' => $collectionName];
}
Generates drop database command.
https://docs.mongodb.com/manual/reference/method/db.dropDatabase/
public array dropDatabase ( ) | ||
return | array |
Command document. |
---|
public function dropDatabase()
{
return ['dropDatabase' => 1];
}
Generates drop indexes command.
public array dropIndexes ( $collectionName, $index ) | ||
$collectionName | string |
Collection name |
$index | string |
Index name or pattern, use |
return | array |
Command document. |
---|
public function dropIndexes($collectionName, $index)
{
return [
'dropIndexes' => $collectionName,
'index' => $index,
];
}
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;
}
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,
];
}
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;
}
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);
}
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:
|
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;
}
Defined in: yii\base\BaseObject::hasMethod()
Returns a value indicating whether a method is defined.
The default implementation is a call to php function method_exists()
.
You may override this method when you implemented the php magic method __call()
.
public boolean hasMethod ( $name ) | ||
$name | string |
The method name |
return | boolean |
Whether the method is defined |
---|
public function hasMethod($name)
{
return method_exists($this, $name);
}
Defined in: yii\base\BaseObject::hasProperty()
Returns a value indicating whether a property is defined.
A property is defined if:
- the class has a getter or setter method associated with the specified name (in this case, property name is case-insensitive);
- the class has a member variable with the specified name (when
$checkVars
is true);
See also:
public boolean hasProperty ( $name, $checkVars = true ) | ||
$name | string |
The property name |
$checkVars | boolean |
Whether to treat member variables as properties |
return | boolean |
Whether the property is defined |
---|
public function hasProperty($name, $checkVars = true)
{
return $this->canGetProperty($name, $checkVars) || $this->canSetProperty($name, false);
}
Defined in: yii\base\BaseObject::init()
Initializes the object.
This method is invoked at the end of the constructor after the object is initialized with the given configuration.
public void init ( ) |
public function init()
{
}
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;
}
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;
}
Generates list indexes command.
public array listIndexes ( $collectionName, $options = [] ) | ||
$collectionName | string |
Collection name |
$options | array |
Command options. Available options are:
|
return | array |
Command document. |
---|
public function listIndexes($collectionName, $options = [])
{
return array_merge(['listIndexes' => $collectionName], $options);
}
Generates 'map-reduce' command.
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:
|
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;
}
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;
}