I am trying to merge data from a collection named reviews into another collection named products. I want to merge all reviews for a given product, into the product in the products collection as an array named reviews.
For example, here is a product object followed by a review object:
A specific product -

A few reviews for the above product -

I have attempted to aggregate the data using the below code but I don't know how to insert them into the products collection.
db.getCollection('reviews').aggregate( [
{ $match: {db_asin: "3866811659"}},
{ $group: {_id: null, reviews : { $push: "$$ROOT" }}},
{ $out : "products.db_asin.3866811659" }
] )
Change the aggregation to product collection and use $lookup to pull reviews from another collection on db_asin.
Something like
db.products.aggregate([
{"$match": {"db_asin": "3866811659"}},
{"$lookup":{
"from":"reviews",
"localField":"db_asin",
"foreignField":"db_asin",
"as":"reviews"
}}
]).forEach(function(doc){
var _id = doc._id;
var reviews = doc.reviews;
db.products.update({"_id" : _id},{"$set": {"reviews" : reviews}})
});
Edit: Added closing bracket at the end of forEach loop
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With