
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 } ] }
Advertisements