Increase mongodb value by %

Viewed 60

I'm learning MongoDB and NodeJs. How to correctly increase weight by 2% stored in DB when making a query without writing new value in DB with NodeJS. Something like that:

    const cargoQuery = Cargo.aggregate([
      {
    **IncreasedWeight**: {$multiply:[weight,{$divide:[2,100]}]}
    .../*and then use this IncreasedWeight elsewhere*/
$match: {
      $or: [
        {cargoType: {$eq: req.query.cRuleADR}, IcreasedWeight: {$lte: req.query.cRuleMaxWeight}}
      ],
      height: {$lte: +req.query.tRuleHeight},
      width: {$lte: +req.query.tRuleWidth},
      clength: {$lte: +req.query.tRuleLength}

Here is my doc:

{
    "_id" : ObjectId("608c5e77291d492820c6b346"),
    "cargoType" : "palletized",
    "description" : "fdsfdsfs",
    "price" : 700,
    "height" : 2,
    "width" : 2,
    "clength" : 2,
    "weight" : 8000,
    "date" : ISODate("2021-04-30T19:45:59.000Z"),
    "userId" : ObjectId("60868c31caafe530e7e2d04a"),
    "__v" : 0
}

Thank you very much for your time

1 Answers

Calculate a percentage by equation in your client language, like (2 / 100) + 1 = 1.02,

  • $expr match expression condition when for internal field operation
  • use $and and condition to construct a condition
const cargoQuery = Cargo.aggregate([
  {
    $match: {
      $and: [
        {
          $or: [
            { cargoType: req.query.cRuleADR },
            {
              $expr: {
                $lte: [{ $multiply: ["$weight", 1.02] }, req.query.cRuleMaxWeight]
              }
            }
          ]
        },
        {
          height: { $lte: +req.query.tRuleHeight },
          width: { $lte: +req.query.tRuleWidth },
          clength: { $lte: +req.query.tRuleLength }
        }
      ]
    }
  }
])
Related