Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
Update only a specific value in a MongoDB document
To update only a specific value, use update() and in that set the new value using $set. Let us create a collection with documents −
> db.demo201.insertOne({"ClientName":"Chris Brown","ClientAge":26});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e3c39ca03d395bdc21346e5")
}
> db.demo201.insertOne({"ClientName":"David Miller","ClientAge":35});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e3c39d403d395bdc21346e6")
}
> db.demo201.insertOne({"ClientName":"Carol Taylor","ClientAge":28});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e3c39e603d395bdc21346e7")
}
Display all documents from a collection with the help of find() method −
> db.demo201.find();
This will produce the following output −
{ "_id" : ObjectId("5e3c39ca03d395bdc21346e5"), "ClientName" : "Chris Brown", "ClientAge" : 26 }
{ "_id" : ObjectId("5e3c39d403d395bdc21346e6"), "ClientName" : "David Miller", "ClientAge" : 35 }
{ "_id" : ObjectId("5e3c39e603d395bdc21346e7"), "ClientName" : "Carol Taylor", "ClientAge" : 28 }
Following is the query to update MongoDB −
> db.demo201.update({"ClientAge":35},{$set:{"ClientName":"John Doe"}},{multi:true});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Display all documents from a collection with the help of find() method −
> db.demo201.find();
This will produce the following output −
{ "_id" : ObjectId("5e3c39ca03d395bdc21346e5"), "ClientName" : "Chris Brown", "ClientAge" : 26 }
{ "_id" : ObjectId("5e3c39d403d395bdc21346e6"), "ClientName" : "John Doe", "ClientAge" : 35 }
{ "_id" : ObjectId("5e3c39e603d395bdc21346e7"), "ClientName" : "Carol Taylor", "ClientAge" : 28 } Advertisements
