From my Orders, as shown below. I would like to $sum
the field Amount
and Total
const OrderSchema = new mongoose.Schema(
{
Person: {
type: String,
trim: true,
required: true,
},
Purchased: {
type: Boolean,
default: false,
},
PurchaseDate: {
type: Date,
},
Amount: {
type: Number,
required: true,
},
Total: {
type: Number,
required: true,
},
},
{ timestamps: true },
);
My Solution:
Order.aggregate([
{
$match: {
OrderDate: {
$gte: start,
$lte: end,
},
Purchased: true,
},
},
{
$group: {
_id: '$Person',
Total: {
$sum: '$Total',
},
Amount: {
$sum: '$Amount',
},
},
},
{
$project: {
Person: '$_id',
Total: '$Total',
Amount: '$Amount',
_id: 0,
},
},
{
$sort: { Person: 1 },
},
])
.then((orders) => {
res.json(orders);
})
.catch((err) => {
res.status(400).json(
{
err: {
name: err.name,
message: err.message,
},
},
);
});
Ok, this works well, but now I have all Orders inside a Invoice
const InvoiceSchema = new mongoose.Schema(
{
Purchased: {
type: Boolean,
default: false,
},
PurchaseDate: {
type: Date,
},
Orders: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Order',
}],
},
{ timestamps: true },
);
And here is my problem, how do I do the same now
Invoice.aggregate([
{
// before?
}
{
$match: {
OrderDate: {
$gte: start,
$lte: end,
},
Purchased: true,
},
},
{
// after?
}
]);