Update quantity in MongoDB based on two conditions?


For this, use UPDATE() method and within that set the two conditions. Let us create a collection with documents −

> db.demo605.insertOne(
...    {
...       _id:1,
...       "Information" : [
...          {
...             "id" : "Product-1",
...             "Quantity" : 50,
...          },
...          {
...             "id" : "Product-2",
...             "Quantity" : 100,
...          },
...       ]
...    }
... );
{ "acknowledged" : true, "insertedId" : 1 }
>
>
> db.demo605.insertOne(
...    {
...       _id:2,
...       "Information" : [
...          {
...             "id" : "Product-1",
...             "Quantity" : 30,
...          },
...          {
...             "id" : "Product-2",
...             "Quantity" : 40,
...          },
...       ]
...    }
... );
{ "acknowledged" : true, "insertedId" : 2 }

Display all documents from a collection with the help of find() method −

> db.demo605.find();

This will produce the following output &mnus;

{ "_id" : 1, "Information" : [
   { "id" : "Product-1", "Quantity" : 50 },
   { "id" : "Product-2", "Quantity" : 100 }
] }
{ "_id" : 2, "Information" : [
   { "id" : "Product-1", "Quantity" : 30 },
   { "id" : "Product-2", "Quantity" : 40 }
] }

Following is the query to update the quantity in MongoDB based on two conditions −

>db.demo605.update({_id:1,"Information.id":"Product1"},
   {$set:{"Information.$.Quantity":1000}}
);
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Display all documents from a collection with the help of find() method −

> db.demo605.find().pretty();

This will produce the following output −

{
   "_id" : 1,
   "Information" : [
      {
         "id" : "Product-1",
         "Quantity" : 1000
      },
      {
         "id" : "Product-2",
         "Quantity" : 100
      }
   ]
}
{
   "_id" : 2,
   "Information" : [
      {
         "id" : "Product-1",
         "Quantity" : 30
      },
      {
         "id" : "Product-2",
         "Quantity" : 40
      }
   ]
}

Updated on: 15-May-2020

135 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements