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 ] }

Updated on: 31-Mar-2020

693 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements