我有以下架构:
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
});
我想进行一个汇总查询,对每个产品求和并添加quantity*price
到total
,然后返回总数。但是,我只知道如果我有多个产品,每个产品作为一个文档,然后对所有文档求和而不是这个。
你可以用$reduce做到这一点:
db.collection.aggregate([{
$addFields: {
"total": {
$reduce: {
input: "$products",
initialValue: '$total',
in: { $add: [{ $multiply: ["$$this.quantity", "$$this.price"] }, '$$value'] }
}
}
}
}])
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句