MongoDB: How can we achive cross-updates with a simple Java Script?!

Let’s say we’ve products and discounts collections as below and we will need to update discount_BOGO ( Buy One Get One ) field by joining on the product Id ( which is _id  below), we can use below simple Java Script and iterate across all documents from discounts.

Below JS will iterate all documents from products collection and for Each document it will match data with _id from discounts and _id from products ; And update discount_BOGO fields with value of price from products collection by diving 2 as shown below.

db.products.find({}).forEach(function(prodDocs) {
if (prodDocs) {
db.discounts.updateMany({ _id : prodDocs._id },
{ $set: {discount_BOGO : prodDocs.price * 0.5}});
}});

  • Ask Question