In my Mongo collection I have array. Now I want to update multiple elements of the same array with one query. Is that possible in mongodb. The details are given below.
{ "_id": ObjectId("585a8b05a43c7d21f4d2e6c1"), "tenantid": "e233W", "shortname": "Sou", "uid": "sou...@abc.com", "subscription_details": [{ "app": "SITE", "active": "Y" }, { "app": "NXO", "active": "Y" }, { "app": "CRM", "active": "Y" }] }
Now in this Record I want to update the value of NXO and CRM to "N" Instead of "Y" in a one query. Individual update I have already done where 2 queries run one for NXO and another one for CRM but need help to achieve this in one query if possible.
Hi Souvik,
Now I want to update multiple elements
of the same array with one query. Is that possible in mongodb.
Updating multiple elements in an array is currently not supported in MongoDB. However, there is a feature request regarding this feature in https://jira.mongodb.org/browse/SERVER-1243. Please upvote the ticket if this feature is important for you.
However, you can use the forEach() method in the mongo
shell to achieve the desired result. For example:
db.collection.find({ "tenantid":"e233W"})
.forEach(function (doc) {
doc.subscription_details.forEach(function (subscription_details) {
if (subscription_details.app === "NXO" || subscription_details.app === "CRM") {
subscription_details.active = "N";
}
});
db.collection.save(doc);
});
Regards,
Tom