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 replace value in an array?
Use $set to replace value in an array. Let us first create a collection with documents −
> db.replaceValueInArrayDemo.insertOne({"StudentScores":[45,56,78]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd7f0421a844af18acdffb7")
}
> db.replaceValueInArrayDemo.insertOne({"StudentScores":[33,90,67]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd7f0521a844af18acdffb8")
}
Following is the query to display all documents from a collection with the help of find() method −
> db.replaceValueInArrayDemo.find().pretty();
This will produce the following output −
{
"_id" : ObjectId("5cd7f0421a844af18acdffb7"),
"StudentScores" : [
45,
56,
78
]
}
{
"_id" : ObjectId("5cd7f0521a844af18acdffb8"),
"StudentScores" : [
33,
90,
67
]
}
Following is the query to replace value in array −
> db.replaceValueInArrayDemo.update({_id: ObjectId("5cd7f0421a844af18acdffb7"), StudentScores:45}, {$set: {'StudentScores.$': 99}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Let us check the document once again −
> db.replaceValueInArrayDemo.find().pretty();
This will produce the following output −
{
"_id" : ObjectId("5cd7f0421a844af18acdffb7"),
"StudentScores" : [
99,
56,
78
]
}
{
"_id" : ObjectId("5cd7f0521a844af18acdffb8"),
"StudentScores" : [
33,
90,
67
]
}Advertisements