大家好,這是我的訂單型號:
const OrderSchema = new Schema({
orderItems: {
name: { type: String, required: true },
qty: { type: Number, required: true },
image: { type: String, required: false },
price: { type: Number, required: true },
product: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Product',
required: true,
},
},
totalPrice: { type: Number, required: true },
paymentMethod: { type: String, required: true },
paymentResult: {
status: { type: String, default: 'Waiting For Payment' }
},
user: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true },
isPaid: { type: Boolean, default: false },
paidAt: { type: Date },
OrderResult: {
status: { type: String, default: 'Waiting For Payment' }
},
isDelivered: { type: Boolean, default: false },
},{timestamps : true})
我確實做了這個聚合來獲取用戶訂單摘要:
const usersOrderSummary = await Order.aggregate(
[
{$match:{} },
{$group: {_id:"$user", TotalSpent: {$sum:"$totalPrice"},TotalOrders: { $sum: 1 }}},
]
)
這個聚合的結果是一個陣列:
{
"usersOrderSummary": [
{
"_id": "6216687c0e0d9122f710a1a6",
"TotalSpent": 0.9,
"TotalOrders": 8
},
{
"_id": "628e4b96a7fd3bad9482a81c",
"TotalSpent": 9.18,
"TotalOrders": 53
}
]
}
我希望您的幫助進行匯總以獲得此結果:
我想進行聚合以收集已完成訂單的總和以及在此已完成訂單中花費的金額總和
已完成訂單的條件,所以我只能在請檢查上面的架構時才認為訂單已完成
isDelivered:true
,因此很清楚知道如何將訂單視為已完成
{
"usersOrderSummary": [
{
"_id": "6216687c0e0d9122f710a1a6",
"TotalSpent": 0.9,
"TotalOrders": 8,
"TotalCompletedOrderSpent": 0.1,
"TotalCompletedOrders": 1,
},
{
"_id": "628e4b96a7fd3bad9482a81c",
"TotalSpent": 9.18,
"TotalOrders": 53
"TotalCompletedOrderSpent": 4,
"TotalCompletedOrderSpent": 2,
}
]
}
uj5u.com熱心網友回復:
使用$cond
db.collection.aggregate([
{
$match: {}
},
{
$group: {
_id: "$user",
TotalSpent: { $sum: "$totalPrice" },
TotalOrders: { $sum: 1 },
TotalCompletedOrderSpent: {
$sum: {
$cond: {
if: { $eq: [ "$isDelivered", true ] },
then: "$totalPrice",
else: 0
}
}
},
TotalCompletedOrders: {
$sum: {
$cond: {
if: { $eq: [ "$isDelivered", true ] },
then: 1,
else: 0
}
}
}
}
}
])
mongoplayground
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/491356.html
