定义
MongoDB\Collection::aggregate()对集合执行聚合框架管道操作。
function aggregate( array $pipeline, array $options = [] ): Traversable
参数
$pipeline: array- Specifies an aggregation pipeline operation.
$options: array指定所需选项的数组。
名称类型说明allowDiskUse
布尔
允许写入临时文件。设置为
true时,聚合阶段可以将数据写入到dbPath目录中的_tmp子目录。batchSize
整型
指定光标的批处理大小,将应用于初始
aggregate命令和任何后续getMore命令。这决定了服务器每次响应中返回的最大文档数。批量大小为
0的特殊之处在于,它仅适用于初始的aggregate命令;后续的getMore命令将使用服务器的默认批量大小。这对于从aggregate快速返回游标或失败结果可能很有用,而无需进行大量的服务器端工作。bypassDocumentValidation
布尔
编解码器
MongoDB\Codec\DocumentCodec
排序规则
数组|对象
Collation allows users to specify language-specific rules for string comparison, such as rules for lettercase and accent marks. When specifying collation, the
localefield is mandatory; all other collation fields are optional. For descriptions of the fields, see Collation Document.如果未指定排序规则但集合具有默认排序规则,则操作将使用为集合指定的排序规则。如果没有为集合或操作指定排序规则,MongoDB 将使用先前版本中用于字符串比较的简单二进制比较。
comment
混合
解释
布尔
指定是否返回有关管道处理的信息。
1.4版本新增。
提示
字符串|数组|对象
要使用的索引。将索引名称指定为字符串或将索引键模式指定为文档。如果指定,查询系统将只考虑使用提示索引的计划。
1.3版本新增。
let
数组|对象
参数名称和值的映射。值必须是常量或不引用文档字段的封闭表达式。然后可以在聚合表达式上下文中将参数作为变量进行访问(例如
$$var)。5.0 之前的服务器版本不支持此功能,如果使用,将导致执行时出现异常。
1.9版本新增。
maxTimeMS
整型
The cumulative time limit in milliseconds for processing operations on the cursor. MongoDB aborts the operation at the earliest following interrupt point.
事务外的
Read concern to use for the operation. Defaults to the collection's read concern.
无法将单个操作的读关注(read concern)指定为ACID 事务的一部分。相反,请在启动ACID 事务时设立
readConcern选项。readPreference
Read preference to use for the operation. Defaults to the collection's read preference.
会话
与操作相关联的客户端会话。
1.3版本新增。
typeMap
阵列
应用游标的类型映射,决定如何将BSON文档转换为PHP值。默认为集合的类型映射。
writeConcern
Write concern to use for the operation. Defaults to the collection's write concern.
无法将单个操作的写关注(write concern)指定为ACID 事务的一部分。相反,请在启动ACID 事务时设立
writeConcern选项。
Return Values
MongoDB\ 驱动程序\Cursor 或 ArrayIterator 对象。在这两种情况下,返回值均为 Traversable。
错误/异常
MongoDB\Exception\UnexpectedValueException ,如果来自服务器的命令响应格式错误。
MongoDB\Exception\UnsupportedException,如果所选服务器使用了选项但不支持选项(例如collation、readConcern、writeConcern)。
MongoDB\Exception\InvalidArgumentException 用于与参数或选项解析相关的错误。
MongoDB\ 驱动程序\Exception\RuntimeException 用于扩展级别的其他错误(例如连接错误)。
行为
示例
以下聚合示例使用名为 names 的集合,并将 first_name 字段分组在一起,计算每个组中的结果总数,并按名称对结果进行排序。
$collection = (new MongoDB\Client)->test->names; $cursor = $collection->aggregate( [ ['$group' => ['_id' => '$first_name', 'name_count' => ['$sum' => 1]]], ['$sort' => ['_id' => 1]], ] );