Reputation: 442
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?
Upvotes: 0
Views: 856
Reputation: 5332
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 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
Upvotes: 1