- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to update after aggregate in MongoDB?
To update documents, you cannot use aggregation pipeline. You can use update(). Let us first create a collection with documents −
> db.demo376.insertOne( ... { ... ... "id" :101, ... ... "details" : [ ... { ... Name:"Chris", ... Age:21, ... Score:45 ... }, ... { ... Name:"David", ... Age:23, ... Score:67 ... }, ... { ... Name:"Bob", ... Age:20, ... Score:54 ... } ... ] ... } ... ) { "acknowledged" : true, "insertedId" : ObjectId("5e5a71b92ae06a1609a00b0d") }
Display all documents from a collection with the help of find() method −
> db.demo376.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5e5a71b92ae06a1609a00b0d"), "id" : 101, "details" : [ { "Name" : "Chris", "Age" : 21, "Score" : 45 }, { "Name" : "David", "Age" : 23, "Score" : 67 }, { "Name" : "Bob", "Age" : 20, "Score" : 54 } ] }
Following is the query to update −
> db.demo376.update( ... {"id" :101}, ... {$inc:{"details.$[d].Age":3}}, ... {arrayFilters: [ {$and:[{"d.Age": 21},{"d.Score": {"$gt":40}} ]}] } ... ) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Display all documents from a collection with the help of find() method −
> db.demo376.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5e5a71b92ae06a1609a00b0d"), "id" : 101, "details" : [ { "Name" : "Chris", "Age" : 24, "Score" : 45 }, { "Name" : "David", "Age" : 23, "Score" : 67 }, { "Name" : "Bob", "Age" : 20, "Score" : 54 } ] }
Advertisements