 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP 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
How do I $set and $push in single update with MongoDB?
For this, simply use update() to update. Let us create a collection with documents −
> db.dem0143.insertOne({"StudentId":1,"Details":{"Name":"Chris"}}); {    "acknowledged" : true,    "insertedId" : ObjectId("5e32eb9efdf09dd6d08539b7") } > db.dem0143.insertOne({"StudentId":2,"Details":{"Name":"David"}}); {    "acknowledged" : true,    "insertedId" : ObjectId("5e32eba5fdf09dd6d08539b8") } Display all documents from a collection with the help of find() method −
> db.dem0143.find();
This will produce the following output −
{ "_id" : ObjectId("5e32eb9efdf09dd6d08539b7"), "StudentId" : 1, "Details" : { "Name" : "Chris" } } { "_id" : ObjectId("5e32eba5fdf09dd6d08539b8"), "StudentId" : 2, "Details" : { "Name" : "David" } } Following is the query to implement $set and $push in a single update −
> db.dem0143.update({_id: ObjectId("5e32eba5fdf09dd6d08539b8")}, {$push: {StudentAge:21}, $set: {"Details.Name":"John Doe"}}); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) Display all documents from a collection with the help of find() method −
> db.dem0143.find();
This will produce the following output −
{ "_id" : ObjectId("5e32eb9efdf09dd6d08539b7"), "StudentId" : 1, "Details" : { "Name" : "Chris" } } { "_id" : ObjectId("5e32eba5fdf09dd6d08539b8"), "StudentId" : 2, "Details" : { "Name" : "John Doe" }, "StudentAge" : [ 21 ] }Advertisements
 