To update all the values, use update() along with multi:true. Let us create a collection with documents −
> db.demo720.insertOne({"SubjectName":"MySQL"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5eaae7ca43417811278f5883")
}
> db.demo720.insertOne({"SubjectName":"Java"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5eaae7ce43417811278f5884")
}
> db.demo720.insertOne({"SubjectName":"C"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5eaae7d143417811278f5885")
}
> db.demo720.insertOne({"SubjectName":"C++"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5eaae7d543417811278f5886")
}Display all documents from a collection with the help of find() method −
> db.demo720.find();
This will produce the following output −
{ "_id" : ObjectId("5eaae7ca43417811278f5883"), "SubjectName" : "MySQL" }
{ "_id" : ObjectId("5eaae7ce43417811278f5884"), "SubjectName" : "Java" }
{ "_id" : ObjectId("5eaae7d143417811278f5885"), "SubjectName" : "C" }
{ "_id" : ObjectId("5eaae7d543417811278f5886"), "SubjectName" : "C++" }Following is the query to update all the values of the field “SubjectName” −
> db.demo720.update({},{$set:{SubjectName:"MongoDB"}},{multi:true});
WriteResult({ "nMatched" : 4, "nUpserted" : 0, "nModified" : 4 })Display all documents from a collection with the help of find() method −
> db.demo720.find();
This will produce the following output −
{ "_id" : ObjectId("5eaae7ca43417811278f5883"), "SubjectName" : "MongoDB" }
{ "_id" : ObjectId("5eaae7ce43417811278f5884"), "SubjectName" : "MongoDB" }
{ "_id" : ObjectId("5eaae7d143417811278f5885"), "SubjectName" : "MongoDB" }
{ "_id" : ObjectId("5eaae7d543417811278f5886"), "SubjectName" : "MongoDB" }