Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Aggregate & insert collection into a different collection in mongodb

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 specific product

A few reviews for the above 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" }
              ] )
like image 642
Dom Bryan Avatar asked Oct 24 '25 03:10

Dom Bryan


1 Answers

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

like image 51
s7vr Avatar answered Oct 25 '25 18:10

s7vr