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
How to update only one property in MongoDB?
To update only one property, use $addToSet in MongoDB. Let us create a collection with documents −
> db.demo336.insertOne({"Name":"Chris","Score":[45,67,78]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e522cb1f8647eb59e562097")
}
> db.demo336.insertOne({"Name":"David","Score":[89,93,47]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e522cb2f8647eb59e562098")
}
Display all documents from a collection with the help of find() method −
> db.demo336.find();
This will produce the following output −
{ "_id" : ObjectId("5e522cb1f8647eb59e562097"), "Name" : "Chris", "Score" : [ 45, 67, 78 ] }
{ "_id" : ObjectId("5e522cb2f8647eb59e562098"), "Name" : "David", "Score" : [ 89, 93, 47 ] }
Following is the query to update only one property in MongoDB −
> db.demo336.update({Name:"David"},{ $addToSet: {Score: [56,34,71] }});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Display all documents from a collection with the help of find() method −
> db.demo336.find();
This will produce the following output −
{ "_id" : ObjectId("5e522cb1f8647eb59e562097"), "Name" : "Chris", "Score" : [ 45, 67, 78 ] }
{ "_id" : ObjectId("5e522cb2f8647eb59e562098"), "Name" : "David", "Score" : [ 89, 93, 47, [ 56, 34, 71 ] ] } Advertisements
