Home > Blockchain >  Mongo aggregation $skip is failing
Mongo aggregation $skip is failing

Time:10-29

I am using this mongo db aggregation pipeline to filter customers via many factors that I'm getting from request parameters. Everything seems to work well except the $skip aggregation. The pipeline refuses to skip even when I hard code the parameters. Help. I welcome any help even pointing out if the pipeline is efficient or not

const result = await Customers.aggregate([
      {
        $match: {
          dateCreated: { $gt: new Date(startDate) },
          dateCreated: { $lt: new Date(endDate) },
        },
      },
      {
        $lookup: {
          from: 'orders',
          localField: '_id',
          foreignField: 'user',
          as: 'ordersValue',
        },
      },
      {
        $lookup: {
          from: 'transactions',
          localField: '_id',
          foreignField: 'user',
          as: 'balance',
        },
      },
      {
        $addFields: {
          balance: { $sum: '$balance.amount' },
          ordersValue: { $sum: '$ordersValue.amount' },
        },
      },
      {
        $match: {
          $and: [
            {
              balance: { $lt: Number(balanceLower) },
            },
            {
              balance: { $gt: Number(balanceHigher) },
            },
          ],
        },
      },
      {
        $match: {
          $and: [
            {
              ordersValue: { $gt: 1 * Number(ordersValueLower) },
            },
            {
              ordersValue: { $lt: 1 * Number(ordersValueHigher) },
            },
          ],
        },
      },
      {
        $facet: {
          count: [{ $count: 'queryCount' }],
          data: [
            {
              $sort: {
                _id: orderFactor,
              },
            },
            {
              $limit: limit * 1,
            },
            {
              $skip: (page - 1) * limit,
            },
          ],
        },
      },
    ]);

    const count = result[0].count[0].queryCount;
    const totalPages = Math.ceil(count / limit);

CodePudding user response:

You should switch the order of the $limit and $skip. $skip should go first:

{
  $skip: (page - 1) * limit,
},
{
  $limit: limit * 1,
},
  • Related