简体   繁体   English

猫鼬聚合,如何执行“选择为”?

[英]Mongoose aggregation, how perform 'select as'?

I have just started working with Mongo Db using Mongoose.js library. 我刚刚开始使用Mongoose.js库使用Mongo Db。 I have two schemas, Orders and Payments. 我有两个模式,订单和付款。 I want to make a simple query to get all orders with property of sum of all payments for that order. 我想做一个简单的查询,以获取具有该订单所有付款总和属性的所有订单。

Schemas 架构

Order 订购

{ name : String }

Payment 付款

{ date : Date, order : Schema.ObjectId, sum : Number }

In mysql I would do it this way: 在mysql中,我会这样做:

select *,(select SUM(sum) from payments where payments.order = orders.id group by payments.order) as sum from orders  

I was looking for aggregation methods to build the query. 我正在寻找用于构建查询的聚合方法。 But all examples I have found is for the single object. 但是我发现的所有示例都是针对单个对象的。 I have no trouble to get the sum for single order (using findOne() and aggregation). 我毫不费力地获得单笔订单的总和(使用findOne()和聚合)。 But how I do it for array of orders? 但是我如何处理订单?

There is no way to do this with just one query in MongoDB with the schema design you have. 在MongoDB中只有一个查询具有您所拥有的模式设计是无法做到这一点的。 Your schema is fine for a relational DB, but it might not be ideal for NoSQL. 您的架构对于关系型数据库来说是很好的选择,但对于NoSQL而言可能不是理想的选择。

With your schema you would have to do two queries: 使用您的模式,您将必须执行两个查询:

  • An aggregation job on payment to sum the payments grouped by order 付款汇总作业,按订单汇总付款
  • A a find(),or findOne(), on order to get the name of the order 一个find()或findOne(),用于获取订单名称

An alternative schema would be to have just one collection of order documents and storing the payments as sub-documents on the order document, eg. 另一种方案是仅拥有一个订单文件集合,并将付款作为子文件存储在订单文件中,例如。 an order would look something like this: 订单看起来像这样:

{ 
   name: "Foo"
   payments: [ { date: xxxx, sum: 42.00}, { date: yyyy, sum: 12.00} ]
}

Take a look at the Mongo documentation on data models for more: http://docs.mongodb.org/manual/data-modeling/#data-models 查看有关数据模型的Mongo文档以了解更多信息: http : //docs.mongodb.org/manual/data-modeling/#data-models

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM