How to update the properties of embedded document?

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?

What have you tried so far? What was the outcome?

The update operator you need is $inc — MongoDB Manual. There are examples to increment and decrement a field.

When working with fields within an array, you need https://docs.mongodb.com/manual/reference/operator/update/positional/ to specify which element to update.

In the update you first specify a query that would look like:
{ "email" : seller_email , "inventory.product_id" : product_id }. The update parameter will look like:
{ "$inc" : { "inventory.$.quantity" : quantity } }.

@Aditya_Gupta2, any followup on this?

If not mark my post as a solution so that other know they can follow the same advice.