Mongodb Shopping Cart Save and Modify Problem

  mongodb, question

The rich document of Mongodb can be used to save the shopping cart information of the user.

userId: {
 cart: [
 productId: 111,
 price: 1.00,
 number: 5

Then the problem arises. If I want to modify the unit price of the commodity 111, do I need to traverse Mongodb to modify the price of the commodity 111 in all users’ shopping carts? Is there another good way? Please advise.

Suppose there is only one item 111 in each shopping cart. According to your data structure above, you can use:

db.cart.updateMany({"userId.cart.productId": 111}, {$set: {"userId.cart.$.price": newPrice}});

It is more reasonable to not save the price as mentioned above. Price is sensitive data for e-commerce, which changes frequently. Redundancy does more harm than good.