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
How can I update all elements in an array with a prefix string?
To update all elements in an array with a prefix string in MongoDB, use forEach() combined with map() to transform each array element and $set to update the array. This approach processes each document individually and applies the prefix to all array elements.
Syntax
db.collection.find().forEach(function (doc) {
var prefixedArray = doc.arrayField.map(function (element) {
return "PREFIX" + element;
});
db.collection.update(
{_id: doc._id},
{$set: {arrayField: prefixedArray}}
);
});
Sample Data
db.replaceAllElementsWithPrefixDemo.insertMany([
{
"StudentNames": [
"John",
"Carol"
]
},
{
"StudentNames": [
"Sam"
]
}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5cd91908b50a6c6dd317ad8e"),
ObjectId("5cd9191cb50a6c6dd317ad8f")
]
}
Example: Add "MR." Prefix
Transform all student names by adding the prefix "MR." ?
db.replaceAllElementsWithPrefixDemo.find().forEach(function (myDocumentValue) {
var prefixValue = myDocumentValue.StudentNames.map(function (myValue) {
return "MR." + myValue;
});
db.replaceAllElementsWithPrefixDemo.update(
{_id: myDocumentValue._id},
{$set: {StudentNames: prefixValue}}
);
});
Verify Result
db.replaceAllElementsWithPrefixDemo.find().pretty();
{
"_id": ObjectId("5cd91908b50a6c6dd317ad8e"),
"StudentNames": [
"MR.John",
"MR.Carol"
]
}
{
"_id": ObjectId("5cd9191cb50a6c6dd317ad8f"),
"StudentNames": [
"MR.Sam"
]
}
How It Works
- forEach() iterates through each document in the collection
- map() transforms each array element by applying the prefix
- $set replaces the entire array with the prefixed version
Conclusion
Use forEach() with map() to add prefixes to all array elements efficiently. This approach processes documents individually and replaces the entire array with transformed values in a single update operation.
Advertisements
