代码之家  ›  专栏  ›  技术社区  ›  fear_matrix

$在MongoDB中添加两个字段值

  •  1
  • fear_matrix  · 技术社区  · 8 年前

    我正试图解决一个问题,我试图通过执行$add on matches.shippingCharge+matches.preownedPrice=total来计算的总成本。

    如果匹配的话,我可以很容易做到。ShippingCharge只有$ShippingCharge,但是由于我从2个集合中提取数据,所以方法似乎不同,我不确定如何做到。

       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函数的总和,其结果将是新的汇总字段。所以我的输出应该是这样的:

    {u'Matches': [{u'ShippingCharge': 200, u'PreownedPrice': 2000, u'Total': 2200 }], u'Product': u'A Way Out', u'Price': u'2,499.00'}
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   Ashh    8 年前

    你需要使用 $add aggregation 要添加的聚合 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" ] } }}
                ])