Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
MongoDB query to update selected fields
To update selected fields, use UPDATE() in MongoDB. The $set is used to set the new value. Let us create a collection with documents −
> db.demo352.insertOne({"Name":"Chris"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e55510af8647eb59e5620ba")
}
> db.demo352.insertOne({"Name":"David"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e55510ef8647eb59e5620bb")
}
> db.demo352.insertOne({"Name":"Bob"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e555112f8647eb59e5620bc")
}
> db.demo352.insertOne({"Name":"Mike"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e555115f8647eb59e5620bd")
}
Display all documents from a collection with the help of find() method −
> db.demo352.find();
This will produce the following output −
{ "_id" : ObjectId("5e55510af8647eb59e5620ba"), "Name" : "Chris" }
{ "_id" : ObjectId("5e55510ef8647eb59e5620bb"), "Name" : "David" }
{ "_id" : ObjectId("5e555112f8647eb59e5620bc"), "Name" : "Bob" }
{ "_id" : ObjectId("5e555115f8647eb59e5620bd"), "Name" : "Mike" }
Following is the query to update selected fields only −
> db.demo352.update({Name:"David"},{$set:{"Name":"Robert"}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Display all documents from a collection with the help of find() method −
> db.demo352.find();
This will produce the following output −
{ "_id" : ObjectId("5e55510af8647eb59e5620ba"), "Name" : "Chris" }
{ "_id" : ObjectId("5e55510ef8647eb59e5620bb"), "Name" : "Robert" }
{ "_id" : ObjectId("5e555112f8647eb59e5620bc"), "Name" : "Bob" }
{ "_id" : ObjectId("5e555115f8647eb59e5620bd"), "Name" : "Mike" }Advertisements