简体   繁体   中英

Mongoose aggregation, how perform 'select as'?

I have just started working with Mongo Db using Mongoose.js library. 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:

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). 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. Your schema is fine for a relational DB, but it might not be ideal for 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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