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
MongoDB query to update only certain fields?
To update only certain fields, use $set. Let us create a collection with documents −
> db.demo265.insertOne({"id":101,"Name":"Chris"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e480d781627c0c63e7dbaa4")
}
> db.demo265.insertOne({"id":102,"Name":"Bob"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e480d7d1627c0c63e7dbaa5")
}
> db.demo265.insertOne({"id":103,"Name":"David"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e480d841627c0c63e7dbaa6")
}
Display all documents from a collection with the help of find() method −
> db.demo265.find();
This will produce the following output −
{ "_id" : ObjectId("5e480d781627c0c63e7dbaa4"), "id" : 101, "Name" : "Chris" }
{ "_id" : ObjectId("5e480d7d1627c0c63e7dbaa5"), "id" : 102, "Name" : "Bob" }
{ "_id" : ObjectId("5e480d841627c0c63e7dbaa6"), "id" : 103, "Name" : "David" }
Following is the query to update only certain fields −
> db.demo265.update({Name:"David"},{$set:{id:10004}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Display all documents from a collection with the help of find() method −
> db.demo265.find();
This will produce the following output −
{ "_id" : ObjectId("5e480d781627c0c63e7dbaa4"), "id" : 101, "Name" : "Chris" }
{ "_id" : ObjectId("5e480d7d1627c0c63e7dbaa5"), "id" : 102, "Name" : "Bob" }
{ "_id" : ObjectId("5e480d841627c0c63e7dbaa6"), "id" : 10004, "Name" : "David" } Advertisements
