Hi Everyone! I’m practising MongoDB basics by building a database for a Shopping Application. For the scope of this question, I’ve 2 collections namely sellers
and products
.
Each seller is having their own inventory which is a list of product_id
and quantity
of the product. The product_id
of the product is taken from the products
collection.
My goal is to update(increase/decrease) the product quantity of a particular product in a particular seller’s inventory, by a given number.
Assumptions to make things simple:
- Every seller has a unique email.
- Every product has a unique name.
The sellers
collection looks like this:
[
{
_id: ObjectId("619b1fc5e6faa4f92e0f163d"),
name: 'seller3',
email: 'seller3@gmail.com',
phone_no: 345678,
rating: 0,
inventory: [
{
product_id: ObjectId("619b1fc5e6faa4f92e0f1642"),
quantity: 20
}
]
},
{
_id: ObjectId("619b1fc5e6faa4f92e0f163e"),
name: 'seller4',
email: 'seller4@gmail.com',
phone_no: 901234,
rating: 0,
inventory: [
{ product_id: ObjectId("619b1fc5e6faa4f92e0f1643"), quantity: 5 }
]
}
]
The products
collection is this:
[
{
_id: ObjectId("619b1fc5e6faa4f92e0f1640"),
name: 'Book',
price: 700,
description: 'Loreum Ipsum',
tags: [ 'non-fiction', 'self-help' ]
},
{
_id: ObjectId("619b1fc5e6faa4f92e0f1641"),
name: 'Keyboard',
price: 500,
description: 'beyboard with backlight',
tags: [ 'accessories', 'hardware', 'gadgets' ]
}
]
So, if I want to decrease a given product (product name will be given) by 2 in seller3’s inventory, what should be the query for that?