Home > Blockchain >  Calculate discount in mongodb
Calculate discount in mongodb

Time:10-11

I'd like to post some products to the body and get back the calculated total amount.
But it's getting complicated for me when need to apply discount in that form:

  • for every $amount of $product the price reduced to $new-price
    (let's say every banana is 1$, if customer buy 3 then price is 2$ (but they can buy as many..))

How can I achieve that?

CodePudding user response:

data

db={
  "orders": [
    {
      "_id": "1",
      "customer_id": "1",
      "items": [
        {
          "product_id": "1",
          "quantity": 2
        },
        {
          "product_id": "2",
          "quantity": 5
        }
      ]
    }
  ],
  "product": [
    {
      "product_id": "1",
      "name": "apple",
      "price": 2,
      "quantity": 1,
      "free": 0
    },
    {
      "product_id": "2",
      "name": "banana",
      "price": 1,
      "quantity": 3,
      "free": 1
    }
  ]
}

aggregate

db.orders.aggregate([
  {
    "$match": {
      _id: "1"
    }
  },
  {
    "$unwind": "$items"
  },
  {
    "$lookup": {
      "from": "product",
      "localField": "items.product_id",
      "foreignField": "product_id",
      "as": "product_docs"
    }
  },
  {
    "$set": {
      "product_doc": {
        "$first": "$product_docs"
      }
    }
  },
  {
    "$project": {
      "total_each": {
        "$multiply": [
          {
            $subtract: [
              "$items.quantity",
              {
                "$multiply": [
                  {
                    $floor: {
                      $divide: [
                        "$items.quantity",
                        "$product_doc.quantity"
                      ]
                    }
                  },
                  "$product_doc.free"
                ]
              }
            ]
          },
          "$product_doc.price"
        ]
      }
    }
  },
  {
    "$group": {
      "_id": "$_id",
      "total": {
        "$sum": "$total_each"
      }
    }
  }
])

result:

apple no discount, banana buy 3 get 1 free

2x2 {5-[floor(5/3)x1]}x1 = 8

[
  {
    "_id": "1",
    "total": 8
  }
]

mongoplayground

  • Related