【问题标题】:Mongoose nodejs - Grouping with arraysMongoose nodejs - 用数组分组
【发布时间】:2013-04-25 15:42:49
【问题描述】:

我有一个具有以下架构的集合:

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

我想对一个 customerId 的所有订单的“金额”进行平均,我可以通过在 customerId 上对金额进行分组来实现这一点。

现在,我希望输出的“amount”字段不仅是“amount”的平均值,而且是“otherPayers”字段的“amount”字段的平均值。

我已经查看了 mapreduce,但我无法让它工作。

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

【问题讨论】:

  • 您能否提供示例输出文档 - 我不确定我能否完全说出您要计算的内容,但我确定它可以通过 mapreduce 完成,我猜它可以通过聚合框架。

标签: node.js mongodb mongoose


【解决方案1】:

我猜您想将 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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-18
    • 2017-12-13
    • 1970-01-01
    • 2013-03-15
    • 2020-07-17
    • 2015-09-07
    • 1970-01-01
    • 2012-02-03
    相关资源
    最近更新 更多