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
Replace an array field value with MongoDB?
To replace an array field value in MongoDB, use the $ positional operator with $set. The positional operator identifies the array element that matches the query condition and replaces it with the new value.
Syntax
db.collection.update(
{ "arrayField": "valueToReplace" },
{ $set: { "arrayField.$": "newValue" } }
);
Sample Data
db.replaceAnArrayFieldValueDemo.insertOne({
"StudentTechnicalSubjects": ["MySQL", "SQL Server", "PL/SQL"]
});
{
"acknowledged": true,
"insertedId": ObjectId("5cea41e0ef71edecf6a1f68f")
}
View Current Document
db.replaceAnArrayFieldValueDemo.find().pretty();
{
"_id": ObjectId("5cea41e0ef71edecf6a1f68f"),
"StudentTechnicalSubjects": [
"MySQL",
"SQL Server",
"PL/SQL"
]
}
Replace Array Element
Replace "SQL Server" with "MongoDB" using the positional operator ?
db.replaceAnArrayFieldValueDemo.update(
{ "StudentTechnicalSubjects": "SQL Server" },
{ $set: { "StudentTechnicalSubjects.$": "MongoDB" } }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })
Verify Result
db.replaceAnArrayFieldValueDemo.find().pretty();
{
"_id": ObjectId("5cea41e0ef71edecf6a1f68f"),
"StudentTechnicalSubjects": [
"MySQL",
"MongoDB",
"PL/SQL"
]
}
Key Points
- The
$operator matches the first array element that satisfies the query condition. - Use
$setwitharrayField.$to replace the matched element's value. - The query condition must match the exact value you want to replace.
Conclusion
The positional operator $ combined with $set provides an efficient way to replace specific values within MongoDB arrays. This approach maintains array structure while updating only the targeted element.
Advertisements
