MongoDB query to update array with another field?


To update array with another field, use $push. Let us create a collection with documents −

> db.demo283.insertOne({"Name":"Chris","Status":["Active","Inactive"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e4ab97ddd099650a5401a75")
}

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

> db.demo283.find();

This will produce the following output −

{ "_id" : ObjectId("5e4ab97ddd099650a5401a75"), "Name" : "Chris", "Status" : [ "Active", "Inactive" ] }

Following is the query to update array with another field −

> db.demo283.update({}, {$push: {Status:{$each:['Regular', 'NotRegular'], '$slice': -4}}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

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

> db.demo283.find();

This will produce the following output −

{ "_id" : ObjectId("5e4ab97ddd099650a5401a75"), "Name" : "Chris", "Status" : [ "Active", "Inactive", "Regular", "NotRegular" ]

Updated on: 31-Mar-2020

256 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements