MongoDB query to update array with another field?

MongoDBDatabaseBig Data Analytics

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" ]
raja
Published on 31-Mar-2020 17:00:44
Advertisements