2016-02-25 21 views
0

我对monogodb很满意,我试图使用聚合框架来获取每个代理的收入总和。monogodb获得子文档中的一个字段的总和

我的数据是这样的:

{ 
    "_id" : ObjectId("56ce2ce5b69c4a909eb50f22"), 
    "property_id" : 5594, 
    "reservation_id" : "3110414.1", 
    "arrival" : "2016-02-24", 
    "los" : 1, 
    "updated" : ISODate("2016-02-24T22:21:27.000Z"), 
    "offer_list" : { 
     "68801" : { 
      "pitched" : "yes", 
      "accepted" : "yes", 
      "prime_price" : "3", 
      "agent_price" : "", 
      "price_per" : "night" 
     }, 
     "63839" : { 
      "pitched" : "yes", 
      "accepted" : "yes", 
      "prime_price" : "8", 
      "agent_price" : "", 
      "price_per" : "night" 
     } 
    }, 
    "status" : "accepted", 
    "comments" : [], 
    "created" : ISODate("2016-02-24T22:21:18.000Z"), 
    "agent_id" : 50941 
} 

对于每个AGENT_ID,我想获得的所有“agent_price”的总和(或“prime_price”如果“agent_price”是无)乘以场“洛杉矶“何时”接受“==”是“。

对于预期的输出上面的例子将是:

{'sum':11, 'agent_id": 50941} 

总和为两个 “接受”, “prime_price”(8 + 3)倍洛斯(1)= 11

我试图使用$展开,但它只适用于列表,而不是对象。任何人都可以帮忙吗?

+0

你知道'prime_price'和'agent_price'都是字符串吗? – styvane

+0

是的。这个例子需要解析为int。 –

+0

@zangw除了所有的“价格”项目都需要数字,例子“数组”结构必须是有效的。你对这个例子的编辑可能太仓促了。 –

回答

0

我怀疑这是可能的聚集,但应该是直接与mapreduce

db.collection.mapReduce(
    function(){ 
     for(key in this.offer_list) { 
      if (this.offer_list[key].accepted == 'yes') { 
       if (this.offer_list[key].agent_price == '') { 
        emit(this.agent_id, this.los * this.offer_list[key].prime_price); 
       } else { 
        emit(this.agent_id, this.los * this.offer_list[key].agent_price); 
       } 
      ] 
     } 
    }, 
    function(agent, values) { 
     return Array.sum(values); 
    } 
) 

对于现实生活中的代码,我还要补充一个query option数据卫生。

相关问题