$mongodb中添加两个字段值
我试图解决一个问题,即我试图通过执行$add-on-Matches来计算总成本。ShippingCharge+Matches.PreownedPrice=total 如果匹配,我本可以轻松完成。ShippingCharge仅为$ShippingCharge,但由于我从2个收集中提取数据,方法似乎有所不同,我不确定如何完成$mongodb中添加两个字段值,mongodb,mongodb-query,aggregation-framework,pymongo,Mongodb,Mongodb Query,Aggregation Framework,Pymongo,我试图解决一个问题,即我试图通过执行$add-on-Matches来计算总成本。ShippingCharge+Matches.PreownedPrice=total 如果匹配,我本可以轻松完成。ShippingCharge仅为$ShippingCharge,但由于我从2个收集中提取数据,方法似乎有所不同,我不确定如何完成 gameresult = db.products.aggregate([ {'$match': {'Platform':variable}},
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}}])
当我运行上述查询时,我的结果是:
{u'Matches': [{u'ShippingCharge': 200, u'PreownedPrice': 2000}], u'Product': u'A Way Out', u'Price': u'2,499.00'}
我想要的是Matches.ShippingCharge+Matches.PreownedPrice和$add函数的总和,结果将是新的total字段。所以我的输出应该是这样的:
{u'Matches': [{u'ShippingCharge': 200, u'PreownedPrice': 2000, u'Total': 2200 }], u'Product': u'A Way Out', u'Price': u'2,499.00'}
您需要使用聚合来添加ShippingCharge
和PreownedPrice
字段
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" ] } }}
])
是比$add
更好的选择,因为它不考虑值是否为日期。