$count: Passes a document to the next stage that contains a count of the number of documents input to the stage.
https://www.mongodb.com/docs/manual/reference/operator/aggregation/count/
就是统计当前stage(聚合管道操作的阶段)存在的文档数量。
$match: Filters the documents to pass only the documents that match the specified condition(s) to the next pipeline stage.
过滤符合条件的数据到下个pipeline stage。
语法
}<br><br>// 以上2个方法的输出结果一样,如下。<br><br>result is :Document{{myCount=4}}<br>
复制代码
$group 操作符
官方定义
The $group stage separates documents into groups according to a "group key". The output is one document for each unique group key. A group key is often a field, or group of fields. The group key can also be the result of an expression. Use the _id field in the $group pipeline stage to set the group key.
大概意思就是把文档做分组。 输出的格式是一条数据有一个唯一的分组键。 这里可以简单类比mysql 的group by分组。
result is :Document{{_id=2014-03-01, perDayQuantity=3, myCount=2}}
result is :Document{{_id=2014-03-15, perDayQuantity=10, myCount=1}}
result is :Document{{_id=2014-04-04, perDayQuantity=30, myCount=2}}
$unwind 操作符
官方定义
Deconstructs an array field from the input documents to output a document for each element. Each output document is the input document with the value of the array field replaced by the element.
大概意思就是把输入文档的数组字段按元素一个个拆分出来,并和原来的数据一并形成一条新文档输出。 好比原来10条数据,其中每条数据都有长度为3的数组,那么拆出来(在元素不重复的情况下),会得到30条数据。
Performs a left outer join to a collection in the same database to filter in documents from the "joined" collection for processing. The $lookup stage adds a new array field to each input document. The new array field contains the matching documents from the "joined" collection.
The $lookup stage passes these reshaped documents to the next stage.
Starting in MongoDB 5.1, $lookup works across sharded collections.
其实可以简单理解类比Mysql的子查询。 会把另外一张表匹配的数据,作为一个数组存入到当前数据中,需要自定义一个字段来接收显示。
类比如下的sql语句
result is :Document{{_id=1.0, item=almonds, price=12.0, quantity=2.0, inventory_docs=[Document{{_id=1.0, sku=almonds, description=product 1, instock=120.0}}]}}
result is :Document{{_id=2.0, item=pecans, price=20.0, quantity=1.0, inventory_docs=[Document{{_id=4.0, sku=pecans, description=product 4, instock=70.0}}]}}
result is :Document{{_id=3.0, inventory_docs=[Document{{_id=5.0, sku=null, description=Incomplete}}, Document{{_id=6.0}}]}}
复制代码
$facet 操作符
官方定义
Processes multiple aggregation pipelines within a single stage on the same set of input documents. Each sub-pipeline has its own field in the output document where its results are stored as an array of documents.
Input documents are passed to the $facet stage only once. $facet enables various aggregations on the same set of input documents, without needing to retrieve the input documents multiple times.
简单来说,就是facet可以实现在facet管道操作完成多个stage管道操作。减少获取输入文档的次数。