NodeJS 我正在使用mongoDB聚合管道,我正在获取记录的总数

cidc1ykv  于 12个月前  发布在  Node.js
关注(0)|答案(1)|浏览(101)

我正在使用MONGODB聚合框架,并试图编写一个通用的分页管道,它给我们提供了记录的总数。当我简单地查询它时,它工作得很好,但当我传递搜索参数时,它给出了总文档的记录数,而不是匹配的记录数。

export const paginate = (prevPipeline: any[], options: IOptions) => {
  const dataPipeline = [...prevPipeline];

  if (options.searchBy) {
    const searchCriteria: any = {};
    options.searchBy.split(',').forEach((searchOption: string) => {
      const [field, searchString, searchOptionStr] = searchOption.split(':');
      if (searchString.trim().length > 0) {
        searchCriteria[field] = {
          $regex: searchString,
          $options: searchOptionStr,
        };
      }
    });
    if (Object.keys(searchCriteria).length > 0) {
      dataPipeline.push({ $match: searchCriteria });
    }
  }

  if (options.sortBy) {
    const sortingCriteria: any = {};
    options.sortBy.split(',').forEach((sortOption: string) => {
      const [key, order] = sortOption.split(':');
      sortingCriteria[key] = order === 'desc' ? -1 : 1;
    });
    dataPipeline.push({ $sort: sortingCriteria });
  } else {
    dataPipeline.push({ $sort: { createdAt: 1 } });
  }

  // Project
  if (options.projectBy) {
    const projectionCriteria: any = {};
    options.projectBy.split(',').forEach((projectOption) => {
      const [key, include] = projectOption.split(':');
      projectionCriteria[key] = include === 'hide' ? 0 : 1;
    });
    dataPipeline.push({ $project: projectionCriteria });
  } else {
    dataPipeline.push({ $project: { createdAt: 0, updatedAt: 0 } });
  }

  // Pagination
  const limit =
    options.limit && parseInt(options.limit.toString(), 10) > 0
      ? parseInt(options.limit.toString(), 10)
      : 10;
  const page =
    options.page && parseInt(options.page.toString(), 10) > 0
      ? parseInt(options.page.toString(), 10)
      : 1;
  const skip = (page - 1) * limit;
  dataPipeline.push({ $skip: skip }, { $limit: limit });

  return [
    {
      $facet: {
        metadata: [{ $count: 'totalCount' }],
        data: dataPipeline,
      },
    },
  ];
};```


I am expecting it should  give the matched record count when I queried and total elements count when I do not query it

字符串

qco9c6ql

qco9c6ql1#

如果你需要totalMatchingCount而不是totalCount,你需要修改你的代码,比如:

const skip = (page - 1) * limit;
// insert code here
const dataPipelineMatch =dataPipeLine;
dataPipeLineMatch.push({ $count: 'totalMatchCount' })
// insert code here
dataPipeline.push({ $skip: skip }, { $limit: limit });

个字符

相关问题