|
6 | 6 | - [状态](#status) |
7 | 7 | - [安装](#install) |
8 | 8 | - [快速开始](#quick-start) |
| 9 | +- [聚合查询(aggregate)](#aggregate) |
9 | 10 | - [深度分页(聚合版,Mongo)](#deep-pagination-agg) |
10 | 11 | - [统一 findPage:游标 + 跳页 + offset + totals](#findpage-unified) |
11 | 12 | - [返回耗时(meta)](#返回耗时meta) |
@@ -76,6 +77,48 @@ const MonSQLize = require('monsqlize'); |
76 | 77 | })(); |
77 | 78 | ``` |
78 | 79 |
|
| 80 | +<a id='aggregate'></a> |
| 81 | +## 聚合查询(aggregate) |
| 82 | +> 提示:可在构造时通过 defaults 配置 aggregateMaxTimeMS(默认 10s)。如需允许落盘,请在本次调用显式传入 allowDiskUse: true。 |
| 83 | +`aggregate(options)` 支持以数组形式传入聚合管道,并在管道中使用 `$lookup` 等操作符进行联表查询。 |
| 84 | + |
| 85 | +- 适用:复杂查询与报表,或需要联表的场景。 |
| 86 | +- 缓存:仅当 `options.cache>0` 时启用;缓存键包含 `op=aggregate | pipelineHash`。 |
| 87 | +- 透传(Mongo 专属):支持在 options 里传 `hint`/`collation`,分别透传至 `aggregate` 的 `hint`/`collation`。 |
| 88 | +> 兼容性提示:`aggregate hint` 需要较新的 MongoDB/Node 驱动版本(建议 MongoDB ≥ 4.2,Node 驱动 ≥ 5.x)。 |
| 89 | +
|
| 90 | +示例: |
| 91 | +```js |
| 92 | +const MonSQLize = require('monsqlize'); |
| 93 | +const { collection } = await new MonSQLize({ |
| 94 | + type: 'mongodb', |
| 95 | + databaseName: 'example', |
| 96 | + config: { uri: 'mongodb://localhost:27017' }, |
| 97 | +}).connect(); |
| 98 | + |
| 99 | +const pipeline = [ |
| 100 | + { |
| 101 | + $lookup: { |
| 102 | + from: 'user', |
| 103 | + let: { userId: { $toObjectId: '$userId' } }, |
| 104 | + pipeline: [ { $match: { $expr: { $eq: ['$_id','$$userId'] } } } ], |
| 105 | + as: 'userInfo' |
| 106 | + } |
| 107 | + }, |
| 108 | + { $match: { status: 'paid' } }, |
| 109 | + { $sort: { createdAt: -1, _id: 1 } }, |
| 110 | + { $limit: 10 } |
| 111 | +]; |
| 112 | + |
| 113 | +// 聚合查询 |
| 114 | +const result = await collection('orders').aggregate(pipeline, { |
| 115 | + cache: 3000, |
| 116 | +}); |
| 117 | +console.log(result); |
| 118 | +``` |
| 119 | +> 说明:当前 Mongo 适配器的 `aggregate` 基于原生驱动实现,未来跨数据库将复用该方法名,以各自最优实现(如 SQL Join)。 |
| 120 | +
|
| 121 | + |
79 | 122 | <a id='deep-pagination-agg'></a> |
80 | 123 | ## 深度分页(聚合版,Mongo) |
81 | 124 | > 提示:可在构造时通过 defaults 配置 findPageMaxLimit(默认 500)。如需聚合允许落盘,请在本次调用显式传入 allowDiskUse: true;未来版本可能提供 cursorSecret 以增强游标防篡改。 |
|
0 commit comments