2013-04-24 79 views
0

分组我有下面的模式集合:猫鼬的NodeJS - 使用数组

{OrderId : id, CustomerId : id, amount: Number, otherPayers : [{name : String, amount : Number}]} 

我想提出的所有订单的客户ID的“量”的平均值,而我能做到这一点通过在平均数量上对customerId进行分组而合计。

现在,我希望输出“金额”字段不仅是“金额”的平均值,还是“otherPayers”字段的“金额”字段的平均值。

我已经看了一下mapreduce,但我不能得到它的工作。

有什么想法?在SQL中,使用子查询会很简单。

+0

你能给例如输出文件 - 我不知道我很能告诉你想计算什么,但我敢肯定它是可行的与MapReduce和我猜测它也可以用聚合框架完成。 – 2013-04-25 07:23:04

回答

0

我猜你想把otherPayers数组里面的所有数值加上文档顶层的数量字段。这里是你如何与聚合框架做到这一点:

unwind = { $unwind : "$otherPayers" }; 
group = { $ group : { _id : "$CustomerId", 
         amt : { $first : "$amount" }, 
         count : { $sum : 1 }, 
         total : { $sum : "$otherPayers.amount" } 
     } }; 
project = { $project : { _id : 0, 
         CustomerId : "$_id", 
         avgPaid : { $divide : [ 
             { $add : [ "$total", "$amt" ] }, 
             { $add : [ "$count", 1 ] } 
         ] } 
} }; 

db.collection.aggregate(unwind, group, project);