How to use the $map Operator with Aggregation In MongoDB
The $map operator in MongoDB is used within the aggregation framework to iterate over elements in an array and apply an expression to each element. It’s particularly useful for transforming or manipulating arrays within documents.
Example 1:
Let’s Multiply the “Age” field of each document in the “members” collection by 2 using the $addFields stage in an aggregation pipeline.
// Aggregation pipeline to update Age by multiplying each element by 2
db.members.aggregate([
{
$addFields: {
Age: { $multiply: ["$Age", 2] } // Multiply each age by 2
}
}
]);
Output:
Explanation: In the above output, we updated the documents in members, where the Age fields are multiplied with 2, from the collection.
Example 2:
Let’s Update the “Country” field in all documents of the “members” collection. If the current value of “Country” is “India”, update it to “Washington”, otherwise, keep the current value.
// Aggregation pipeline to update Country from "India" to "Sri Lanka"
db.members.aggregate([
{
$addFields: {
Country: {
$cond: {
if: { $eq: ["$Country", "India"] },
then: "Washington",
else: "$Country"
}
}
}
}
]);
Output:
Explanation: In the above output, we updated the documents in members, where the country contains india update it as washington, from the collection.
How to Update Multiple Array Elements in MongoDB?
MongoDB, the popular NoSQL database, offers powerful features for manipulating data, including the ability to update multiple array elements within a document. Efficiently updating multiple elements in an array can be important in various scenarios, such as managing user preferences, and handling inventory quantities.
In this article, we will learn about How to Update Multiple Array Elements in MongoDB by understanding various methods along with the multiple examples and so on.
Contact Us