我对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”为None)的总和,当“accepted”==“yes”时乘以字段“los”。
对于上面的示例,预期输出将是:
{'sum':11, 'agent_id": 50941}
总和是两个“接受”“prime_price”(8 + 3)次los(1)= 11.
我尝试使用$ unwind但它只适用于列表,而不是对象。任何人都可以提供帮助吗?
答案 0 :(得分: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。