0

I have the following schema:

var orderSchema = new mongoose.Schema({
    deleted: Boolean,
    clientName: String,
    clientPhone: String,
    products: [{
        name: String,
        quantity: Number,
        price: Number
    }],
    observations: String,
    date: {
        type: Date,
        default: Date.now
    },
    seller: String,
    orderNumber: Number,
    total: Number
});

And I want to make an aggregate query that sums each product and add quantity*price to the total, and return me the total. However, I only know how to do it if I had multiple products, each one as a document, and then sum over all the documents but not this.

1 Answer 1

1

You can do this with $reduce :

db.collection.aggregate([{
    $addFields: {
        "total": {
            $reduce: {
                input: "$products",
                initialValue: '$total',
                in: { $add: [{ $multiply: ["$$this.quantity", "$$this.price"] }, '$$value'] }
            }
        }
    }
}])

Test : MongoDB-Playground

Sign up to request clarification or add additional context in comments.

4 Comments

what is total??
@GuerlandoOCs : I didn't get that ? total = total + sum of quantity*price of all products..
You add a field "total" into the document. What if I want to return a new document only with the total field? instead of addFields I return a new document
@GuerlandoOCs : You can try with $project instead $addFields, also add _id:0 in project to exclude that as well.. Generally $addFields would replace exiting Total field with new value or if it not there it will a new field to column..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.