跳到主要内容

count

统计满足条件的实体数量。常与分页查询一起使用。

方法签名

count(options: CountOptions<T>): Observable<number>

参数说明

interface CountOptions<T> {
// 查询条件
where: RuleGroup<InstanceType<T>>;

// 预留:分组统计(当前未实现)
// groupBy?: string[];
}

说明:当前 groupBy 暂不支持(会抛出错误),请在应用层聚合。

使用场景

1. 基础计数

import { firstValueFrom, switchMap } from 'rxjs';

const total = await rxdb.pipe(
switchMap(() => Todo.count({
where: { combinator: 'and', rules: [] }
})),
firstValueFrom
);

2. 条件计数

// 已完成数量
const completed = await rxdb.pipe(
switchMap(() => Todo.count({
where: {
combinator: 'and',
rules: [ { field: 'completed', operator: '=', value: true } ]
}
})),
firstValueFrom
);

3. 搭配分页查询

async function getPagedTodos(page: number, pageSize: number) {
const where = { combinator: 'and' as const, rules: [] };

const [items, total] = await Promise.all([
rxdb.pipe(
switchMap(() => Todo.find({ where, orderBy: [{ field: 'createdAt', sort: 'desc' }], limit: pageSize, offset: (page - 1) * pageSize })),
firstValueFrom
),
rxdb.pipe(
switchMap(() => Todo.count({ where })),
firstValueFrom
)
]);

return { items, total, page, pageSize, totalPages: Math.ceil(total / pageSize) };
}

关系字段计数

where 支持关系字段(如 owner.id, parent.title),底层会自动生成 JOIN。

// 某用户的 Todo 数量
const userTodoCount = await rxdb.pipe(
switchMap(() => Todo.count({
where: {
combinator: 'and',
rules: [ { field: 'owner.id', operator: '=', value: userId } ]
}
})),
firstValueFrom
);

最佳实践

  • 与列表查询共享 where,可避免重复构造条件
  • 大范围统计可结合缓存或更粗粒度策略
  • 当使用 findAll 已取回全集时,可直接 items.length 代替再次统计

参考