mongoose-aggregate-paginate-v2 icon indicating copy to clipboard operation
mongoose-aggregate-paginate-v2 copied to clipboard

$lookup performance

Open samuelpares opened this issue 3 years ago • 1 comments

I'm using lookup just to return associated data. I'm not perfomring any stage for filtering/matching. So for what I understand, my lookups stages are executed before the pagination. Is there a way to performe pagination before? It would increase a lot the performance.

async findAll(query: QueryDto) {
    const { perPage, page } = query;

    const options = {
      limit: perPage,
      page: page,
      pagination: perPage > 0,
    };

    const pipeline = this.aggregateModel.aggregate();
    pipeline.sort({ createdAt: -1 });
    pipeline.lookup({
      from: 'accounts',
      localField: 'account',
      foreignField: '_id',
      as: 'account',
    });
    pipeline.lookup({
      from: 'businessnumbers',
      localField: 'businessNumber',
      foreignField: '_id',
      as: 'businessNumber',
    });
    pipeline.lookup({
      from: 'templates',
      localField: 'template',
      foreignField: '_id',
      as: 'template',
    });
    pipeline.unwind({ path: '$account' });
    pipeline.unwind({ path: '$businessNumber' });
    pipeline.unwind({ path: '$template' });

    return await this.aggregateModel.aggregatePaginate(pipeline, options);
  }

samuelpares avatar Nov 03 '22 13:11 samuelpares