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
-
Economics & Finance
Selected Reading
MongoDB query to replace value in an array?
To replace a specific value in a MongoDB array, use the $set operator combined with the $ positional operator. The positional operator identifies the array element that matches the query condition and allows you to update it.
Syntax
db.collection.update(
{ "arrayField": "valueToReplace" },
{ $set: { "arrayField.$": "newValue" } }
);
Sample Data
db.replaceValueInArrayDemo.insertMany([
{ "StudentScores": [45, 56, 78] },
{ "StudentScores": [33, 90, 67] }
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5cd7f0421a844af18acdffb7"),
ObjectId("5cd7f0521a844af18acdffb8")
]
}
Display all documents to verify the data ?
db.replaceValueInArrayDemo.find().pretty();
{
"_id": ObjectId("5cd7f0421a844af18acdffb7"),
"StudentScores": [ 45, 56, 78 ]
}
{
"_id": ObjectId("5cd7f0521a844af18acdffb8"),
"StudentScores": [ 33, 90, 67 ]
}
Example: Replace Value 45 with 99
db.replaceValueInArrayDemo.update(
{ _id: ObjectId("5cd7f0421a844af18acdffb7"), StudentScores: 45 },
{ $set: { 'StudentScores.$': 99 } }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })
Verify Result
db.replaceValueInArrayDemo.find().pretty();
{
"_id": ObjectId("5cd7f0421a844af18acdffb7"),
"StudentScores": [ 99, 56, 78 ]
}
{
"_id": ObjectId("5cd7f0521a844af18acdffb8"),
"StudentScores": [ 33, 90, 67 ]
}
Key Points
- The
$operator identifies the first matching array element in the query condition. - Include the target value in both the query condition and the array field to ensure precise matching.
- This method only updates the first occurrence of the matching value.
Conclusion
Use $set with the $ positional operator to replace specific values in MongoDB arrays. The query condition must include the target value to identify which array element to update.
Advertisements
