SortByCount Operation¶
SortByCountOperation đại diện cho stage $sortByCount của MongoDB. Stage này nhóm các document theo một biểu thức/field và trả về số lượng mỗi nhóm, đồng thời tự động sắp xếp giảm dần theo count.
import { SortByCountOperation } from 'red-aggregation/operations/sortByCountOperation';
import { Fields } from 'red-aggregation/aggregate/field';
Phương thức¶
- new SortByCountOperation(fieldRef: Field)
- new SortByCountOperation(expression: AggregationExpression)
- new SortByCountOperation(document: BSON)
Group theo field¶
new SortByCountOperation(Fields.field('category')).toDocument(context);
// => { $sortByCount: '$category' }
Group theo AggregationExpression¶
const expr = { $concat: ['$brand', '-', '$category'] };
new SortByCountOperation(expr).toDocument(context);
// => { $sortByCount: { $concat: ['$brand', '-', '$category'] } }
Group theo raw BSON¶
new SortByCountOperation({ $substr: ['$name', 0, 3] }).toDocument(context);
// => { $sortByCount: { $substr: ['$name', 0, 3] } }
Lưu ý sử dụng¶
- Tham số truyền cho constructor phải hợp lệ (không
null/undefined). - Khi truyền
Field, giá trị sẽ được ánh xạ thành'$field'thông quacontext. - Khi truyền
AggregationExpression, nội dung sẽ được lấy quaexpression.toDocument(context). $sortByCounttương đương với{$group: { _id: <expr>, count: {$sum: 1} } }rồi{$sort: { count: -1 } }, nhưng gọn hơn trong một stage.