Reputation: 4960
I am trying to solve an issue where I am trying to calculate the total cost of by doing a $add on Matches.ShippingCharge + Matches.PreownedPrice = Total.
I could have done it easily if Matches.ShippingCharge was only $ShippingCharge but since I am pulling data from 2 collection the approach seems to be different and I am not sure how to do it.
gameresult = db.products.aggregate([
{'$match': {'Platform':variable}},
{'$lookup':{'from': 'vendorgames','localField': 'Product','foreignField': 'Product','as': 'Matches'}},
{'$project': {'_id':0,'Product':'$Product','Price':'$Price','Matches.ShippingCharge':1,'Matches.PreownedPrice':1}}])
When I run the above query my result is so:
{u'Matches': [{u'ShippingCharge': 200, u'PreownedPrice': 2000}], u'Product': u'A Way Out', u'Price': u'2,499.00'}
What I want is the sum of Matches.ShippingCharge + Matches.PreownedPrice with $add function where the result will be the new total field. So my output should be like so:
{u'Matches': [{u'ShippingCharge': 200, u'PreownedPrice': 2000, u'Total': 2200 }], u'Product': u'A Way Out', u'Price': u'2,499.00'}
Upvotes: 1
Views: 2297
Reputation: 46441
You need to use $add aggregation
aggregation to add ShippingCharge
and PreownedPrice
fields
gameresult = db.products.aggregate([
{'$match': {'Platform':variable}},
{'$lookup':{'from': 'vendorgames','localField': 'Product','foreignField': 'Product','as': 'Matches'}},
{'$project': {'_id':0,
'Product':'$Product',
'Price':'$Price',
'Matches.ShippingCharge':1,
'Matches.PreownedPrice':1,
'total': { $add: [ "$Matches.ShippingCharge", "$Matches.PreownedPrice" ] } }}
])
Upvotes: 2