我有一个商店库存集合,分别包含“数量”和“价格”字段
{
"_id": "5dd033a1a9133424a8ae2924",
"name": "Belt",
"description": "Auto",
"price": 7,
"quantity": 60,
"supplier": "Thomson",
"taxable": true,
"createdAt": "2019-11-16T17:36:33.753Z",
"updatedAt": "2020-01-11T09:33:27.756Z",
"__v": 0,
"orders": []
},
我希望能够获得商店中所有商品的总成本,即所有商品的价格*数量之和
// model
const mongoose= require('mongoose');
//create Schema
const InventorySchema = new mongoose.Schema({
// _id: mongoose.Schema.Types.ObjectId,
name : { type: String, required: true },
description : { type: String, required: true },
price : { type: Number, required: true },
quantity : { type: Number, required: true },
supplier : String,
taxable : Boolean,
orders: [{quantity: Number,issuedBy:String,collectedBy:String,department:String}]
},{timestamps:true});
答案 0 :(得分:2)
一个简单的$group
阶段应该可以解决问题:
db.collection.aggregate([
{
$group: {
_id: null,
total: {$sum: {$multiply: ["$price", "$quantity"]}}
}
}
])