How to use the $set Operator with Multiple Indexes In MongoDB
The $set operator in MongoDB is used within update operations to set a specific field to a given value. It can be used to create a new field if it doesn’t exist or update an existing field with a new value.
Example 1:
Let’s create a MongoDB collection named ‘members’ and insert sample documents. Then, we’ll update the documents for members who’s Age greater than 26, from the collection.
// Updating elements of documents for members who are aged 26 or above
db.members.updateMany(
{ Age: { $gte: 26 } },
{ $set: { Age: 40 } }
);
// Displaying documents after the update
db.members.find();
Output:
Explanation: In the above output, we updated the documents in members who Age is greater than 26, from the collection.
Example 2:
Let’s Update the “Country” field in multiple documents of the “members” collection where the “Country” is currently set to “India” to “Sri Lanka“.
// Update documents where Country is "India" to "Sri Lanka"
db.members.updateMany(
{ Country: "India" },
{ $set: { Country: "Sri Lanka" } }
);
// Displaying documents after the update
db.members.find();
Output:
Explanation: In the above output, we updated the documents in members,where the country field India isupdated as srilanka 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