Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Mongo aggregation $skip is failing

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);

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

{
  $skip: (page - 1) * limit,
},
{
  $limit: limit * 1,
},
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading