MongoDB - Aggregate and write in sales table

Viewed 42

Assume there is a collection names productRecord which stores the documents in following way:

{
  _id : //id,
  productName : // product name,
  productPrice : //price of product,
  productQuantity: //quantity of product in stock
}

and I have recieved sale object(recieved after sale is made) in format:

var sale = {
  id : //id
  products : [
     {productId : //id1, qty : //quantity sold},
     {productId : //id2, qty : //quantity sold},
     {productId : //id3, qty : //quantity sold}
   ]
}

The id is unique to the sale. I need enter the value in another table named 'saleRecords' in format:

{
  id: //id,
  products : [
     {productId : //id1, qty : //quantity sold},
     {productId : //id2, qty : //quantity sold},
     {productId : //id3, qty : //quantity sold}
   ] // same as above ,
   totalsaleprice: //this will be sale.qty * productRecord.productPrice (both related using productId)
}

But the price is in the 'productRecord' collection, the qty in the sales record objects and the value needs to be entered in 'salesRecords' connection. How do I write a query for this?

0 Answers
Related