SELECT
5 methodsSELECT 语句中可用的子句。
{ $match: <query> }从表中读取行,可选按布尔条件过滤。
Parameters
| Name | Type | Description |
|---|---|---|
| query | object | Selector document. |
Returns
Stage
Example
mongodb
{ $match: { status: 'active', age: { $gte: 18 } } }{ $group: { _id: <expr>, <field>: { <accumulator>: <expr> } } }基于连接谓词组合两个表的行;支持 INNER、LEFT、RIGHT、FULL。
Parameters
| Name | Type | Description |
|---|---|---|
| _id | expression | Group key expression; null groups all documents. |
| accumulator | string | $sum, $avg, $max, $min, $push, $addToSet, etc. |
Returns
Stage
Example
mongodb
{ $group: { _id: '$dept', avgSalary: { $avg: '$salary' } } }{ $project: <specification> }按列出的列分组行并应用聚合函数,用 HAVING 过滤分组。
Parameters
| Name | Type | Description |
|---|---|---|
| specification | object | Field inclusion (1), exclusion (0) or expression. |
Returns
Stage
Example
mongodb
{ $project: { name: 1, age: 1, _id: 0 } }{ $lookup: { from, localField, foreignField, as } }按给定列排序结果集并限制返回行数。
Parameters
| Name | Type | Description |
|---|---|---|
| from | string | Foreign collection name. |
| localField | string | Field from the input documents. |
| foreignField | string | Field from the foreign collection documents. |
| as | string | Output array field name. |
Returns
Stage
Example
mongodb
{ $lookup: { from: 'orders', localField: '_id', foreignField: 'userId', as: 'orders' } }{ $sort: { <field>: 1 | -1 } }Aggregation stage that sorts documents by the given fields; 1 ascending, -1 descending.
Parameters
| Name | Type | Description |
|---|---|---|
| field | string | Field path to sort by. |
Returns
Stage
Example
mongodb
{ $sort: { createdAt: -1 } }