Ryan Soderberg
Ryan Soderberg

Reputation: 772

Add 1 to $size in Mongodb

I am trying to find someone's position in a list with the number of referrals they have. I want to be able to calculate what their position would be if they had 1 more referral.

This works perfectly to order my data set by the number of items in the "referrals" array each user has. I try to edit it so if the emails match then: 1 + {$size: "$referred"}, but it prints out as lengthOfArray: '1[object Object]' },

How would I go about increasing lengthOfArray by 1 when the emails match?

  const addedSort = await User.aggregate([
    {
      $addFields: {
        lengthOfArray:  {
          $cond: { if: { $eq: [ "$email", req.params.email ] }, then: {
            $size: "$referred"
          }, else: {
            $size: "$referred"
          } }
        }
      }
    },
    {
      $sort: {
        lengthOfArray: -1,
        created: -1
      }
    }
  ]);

Upvotes: 3

Views: 198

Answers (1)

Mohammad Faisal
Mohammad Faisal

Reputation: 2432

You can use $add operator of mongodb

Syntax

{ $add: [ <expression1>, <expression2>, ... ] }

and your Code become something like this,

const addedSort = await User([
  {
    $addFields: {
      lengthOfArray: {
        $cond: {
          if: {
            $eq: [
              "$email",
              req.params.email
            ]
          },
          then: {
            $add: [
              {
                $size: "$referred"
              },
              1
            ]
          },
          else: {
            $size: "$referred"
          }
        }
      }
    }
  },
  {
    $sort: {
      lengthOfArray: -1,
      created: -1
    }
  }
])

Shorter Version (Same as Above but little Shorter)

const addedSort = await User([
    {
        $addFields: {
            lengthOfArray:
            {
                $cond: [
                    { $eq: ["$email", req.params.email] },    // Condition
                    { $add: [{ $size: "$reffered" }, 1] },   // If Condition True
                    { $size: "$reffered" }                    // False Condition
                ]
            }
        }
    },
    {
        $sort: {
            lengthOfArray: -1,
            created: -1
        }
    }
])

Upvotes: 1

Related Questions