MongoDB\Driver\Query: : _ _construct
(mongodb >=1.0.0)
MongoDB\Driver\Query::__construct — Create a new Query
Description
Constructs a new MongoDB\Driver\Query, which is an immutable value object that represents a database query. The query may then be executed with MongoDB\Driver\Manager::executeQuery().
Liste de paramètres
-
filter
(array|object) -
L'» attribut de la requête. Un attribut vide va faire correspondre tous les documents de la collection.
Note: Lors de l'évaluation des critères de requête, MongoDB compare les type et les valeurs en fonction de leur propre » règles de comparaison pour les types BSON, qui diffère des règles de comparaison et de manipulation des type de PHP. Lors de la correspondance d'un type BSON spcécial, les critères de requête doivent utiliser la classe BSON (ex. : utiliser MongoDB\BSON\ObjectId pour correspondre à un » ObjectId).
-
queryOptions
-
queryOptions Option Type Description allowPartialResults boolean For queries against a sharded collection, returns partial results from the mongos if some shards are unavailable instead of throwing an error.
Falls back to the deprecated "partial" option if not specified.
awaitData boolean Use in conjunction with the "tailable" option to block a getMore operation on the cursor temporarily if at the end of data rather than returning no data. After a timeout period, the query returns as normal. batchSize integer The number of documents to return in the first batch. Defaults to 101. A batch size of 0 means that the cursor will be established, but no documents will be returned in the first batch.
In versions of MongoDB before 3.2, where queries use the legacy wire protocol OP_QUERY, a batch size of 1 will close the cursor irrespective of the number of matched documents.
collation array|object » Collation permet aux utilisateurs de spécifier des règles spécifiques au langage pour la comparaison des chaînes, par exemple, des règles pour les majuscules ou les accents. Lors de la spécification d'une collation, le champ "locale" est obligatoire ; tous les autres champs de la collation sont optionnels. Pour la description de ces champs, reportez-vous au » document Collation.
Si la collation n'est pas spécifiée mais que la collection a une collation par défaut, l'opération utilisera la collation spécifiée pour la collection. Si aucune collation n'est spécifiée pour la collection ou pour l'opération, MongoDB utilisera le binaire simple de comparaison utilisé dans les versions précédentes pour les comparaisons des chaînes.
Cette option est disponible en MongoDB 3.4+ et une exception sera émise au moment de l'exécution si elle est spécifiée dans une version antérieure.
comment string A comment to attach to the query to help interpret and trace query profile data.
Falls back to the deprecated "$comment" modifier if not specified.
exhaust boolean Stream the data down full blast in multiple "more" packages, on the assumption that the client will fully read all data queried. Faster when you are pulling a lot of data and know you want to pull it all down. Note: the client is not allowed to not read all the data unless it closes the connection.
This option is not supported by the find command in MongoDB 3.2+ and will force the driver to use the legacy wire protocol version (i.e. OP_QUERY).
explain boolean If
TRUE
, the returned MongoDB\Driver\Cursor will contain a single document that describes the process and indexes used to return the query.Falls back to the deprecated "$explain" modifier if not specified.
This option is not supported by the find command in MongoDB 3.2+ and will only be respected when using the legacy wire protocol version (i.e. OP_QUERY). The » explain command should be used on MongoDB 3.0+.
hint string|array|object Index specification. Specify either the index name as a string or the index key pattern. If specified, then the query system will only consider plans using the hinted index.
Falls back to the deprecated "hint" option if not specified.
limit integer The maximum number of documents to return. If unspecified, then defaults to no limit. A limit of 0 is equivalent to setting no limit.
A negative limit is will be interpreted as a positive limit with the "singleBatch" option set to
TRUE
. This behavior is supported for backwards compatibility, but should be considered deprecated.max array|object The exclusive upper bound for a specific index.
Falls back to the deprecated "$max" modifier if not specified.
maxAwaitTimeMS integer Positive integer denoting the time limit in milliseconds for the server to block a getMore operation if no data is available. This option should only be used in conjunction with the "tailable" and "awaitData" options.
maxScan integer AvertissementThis option is deprecated and should not be used.
Positive integer denoting the maximum number of documents or index keys to scan when executing the query.
Falls back to the deprecated "$maxScan" modifier if not specified.
maxTimeMS integer The cumulative time limit in milliseconds for processing operations on the cursor. MongoDB aborts the operation at the earliest following interrupt point.
Falls back to the deprecated "$maxTimeMS" modifier if not specified.
min array|object The inclusive lower bound for a specific index.
Falls back to the deprecated "$min" modifier if not specified.
modifiers array » Meta operators modifying the output or behavior of a query. Use of these operators is deprecated in favor of named options. noCursorTimeout boolean Prevents the server from timing out idle cursors after an inactivity period (10 minutes). oplogReplay boolean Internal use for replica sets. To use oplogReplay, you must include the following condition in the filter:
[ 'ts' => [ '$gte' => <timestamp> ] ]
projection array|object The » projection specification to determine which fields to include in the returned documents.
If you are using the ODM functionality to deserialise documents as their original PHP class, make sure that you include the __pclass field in the projection. This is required for the deserialization to work and without it, the driver will return (by default) a stdClass object instead.
readConcern MongoDB\Driver\ReadConcern A read concern to apply to the operation. By default, the read concern from the MongoDB Connection URI will be used.
This option is available in MongoDB 3.2+ and will result in an exception at execution time if specified for an older server version.
returnKey boolean If
TRUE
, returns only the index keys in the resulting documents. Default value isFALSE
. IfTRUE
and the find command does not use an index, the returned documents will be empty.Falls back to the deprecated "$returnKey" modifier if not specified.
showRecordId boolean Determines whether to return the record identifier for each document. If
TRUE
, adds a top-level "$recordId" field to the returned documents.Falls back to the deprecated "$showDiskLoc" modifier if not specified.
singleBatch boolean Determines whether to close the cursor after the first batch. Defaults to FALSE
.skip integer Number of documents to skip. Defaults to 0. slaveOk boolean Allow query of replica set secondaries snapshot boolean AvertissementThis option is deprecated and should not be used.
Prevents the cursor from returning a document more than once because of an intervening write operation.
Falls back to the deprecated "$snapshot" modifier if not specified.
sort array|object The sort specification for the ordering of the results.
Falls back to the deprecated "$orderby" modifier if not specified.
tailable boolean Returns a tailable cursor for a capped collection.
Erreurs / Exceptions
- Lance une exception MongoDB\Driver\InvalidArgumentException lors d'une erreur survenue pendant l'analyse d'un argument.
Historique
Version | Description |
---|---|
1.5.0 |
The "maxScan" and "snapshot" options are deprecated. |
1.3.0 |
Added the "maxAwaitTimeMS" option. |
1.2.0 |
Added the "allowPartialResults", "collation", "comment", "hint", "max", "maxScan", "maxTimeMS", "min", "returnKey", "showRecordId", and "snapshot" options. Renamed the "partial" option to "allowPartialResults". For backwards compatibility, "partial" will still be read if "allowPartialResults" is not specified. Removed the "slaveOk" option, which is obsolete. For queries using the legacy wire protocol OP_QUERY, the driver will set the slaveOk bit as needed in accordance with the » Server Selection Specification. |
1.1.0 | Added the "readConcern" option. |
Exemples
Exemple #1 MongoDB\Driver\Query::__construct() example
<?php
/* Select only documents authord by "bjori" with at least 100 views */
$filter = [
'author' => 'bjori',
'views' => [
'$gte' => 100,
],
];
$options = [
/* Only return the following fields in the matching documents */
'projection' => [
'title' => 1,
'article' => 1,
],
/* Return the documents in descending order of views */
'sort' => [
'views' => -1
],
];
$query = new MongoDB\Driver\Query($filter, $options);
$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');
$readPreference = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_PRIMARY);
$cursor = $manager->executeQuery('databaseName.collectionName', $query, $readPreference);
foreach($cursor as $document) {
var_dump($document);
}
?>
Document créé le 30/01/2003, dernière modification le 26/10/2018
Source du document imprimé : https://www.gaudry.be/php-rf-mongodb-driver-query.construct.html
L'infobrol est un site personnel dont le contenu n'engage que moi. Le texte est mis à disposition sous licence CreativeCommons(BY-NC-SA). Plus d'info sur les conditions d'utilisation et sur l'auteur.
Références
Ces références et liens indiquent des documents consultés lors de la rédaction de cette page, ou qui peuvent apporter un complément d'information, mais les auteurs de ces sources ne peuvent être tenus responsables du contenu de cette page.
L'auteur de ce site est seul responsable de la manière dont sont présentés ici les différents concepts, et des libertés qui sont prises avec les ouvrages de référence. N'oubliez pas que vous devez croiser les informations de sources multiples afin de diminuer les risques d'erreurs.