Aleem Uddin
Aleem Uddin

Reputation: 41

How to tackle atomic transaction in mongodb

I have a store where item price is determined based on the quantity available, so whenever user request items, I have to calculate price based on the requested quantity

I have to implement price calculation in an atomic way so that if a transaction occurs during calculation of an ongoing transaction and the price or availableQuantity changes, it should not affect both transactions.

Initial Database

{
   "_id": "1",
   "availableQuantity": 10,
   "pricePerItem": 15
},
{
   "_id": "2",
   "availableQuantity": 5,
   "pricePerItem": 10
},
{
   "_id": "3",
   "availableQuantity": 6,
   "pricePerItem": 20
}

It means that
I can sell 5 items with price 10 / item
next 10 items with price 15 / item
next 6 items with price 20 / item

senario:

User "A" wants to buy 8 items, price will be calculated like this
First, the minimum price object will be selected in our case it is _Id: "2"
5 items will be taken from this object then price = 10*5 = 50

updated database

{
   "_id": "1",
   "availableQuantity": 10,
   "pricePerItem": 15
},
{
   "_id": "3",
   "availableQuantity": 6,
   "pricePerItem": 20
}

Remaining 3 items will be taken from minimum price object which is _id: "1"
Price for 3 items will be price = 3*15 = 45

Total price for user "A" 8 items will be total price = 50 + 45 = 95

Final Database

{
   "_id": "1",
   "availableQuantity": 7,
   "pricePerItem": 15
},
{
   "_id": "3",
   "availableQuantity": 6,
   "pricePerItem": 20
}

Problem

During user "A" transaction if user "B" is requesting 4 items then how should we determine the correct prices.

Note: Many transactions are expected to happen simultaneously

Upvotes: 1

Views: 283

Answers (1)

Mustehssun Iqbal
Mustehssun Iqbal

Reputation: 566

Mongodb does not have support for transactions. There are not-so-popular npm packages which imitate transactional behaviour on the application level but that's it :(

Upvotes: 0

Related Questions