一个分组查询的例子:
model.aggregate([{$match: ops}, {$unwind: '$details'}, {$sort: {create_at: -1}}, {
$group: {
_id: {
promotion_id: "$promotion_id",
product_id: '$details.product_id',
need_pay: '$need_pay'
},
product_name: {$first:"$details.name"},
price: {$max: "$details.price"},
amount: {$sum: "$details.amount"},
packing: {$sum: "$details.packing"},
quantity: {$sum: "$details.quantity"}
}
}, {$match: ops2}, {
$group: {
_id: {
promotion_id: "$_id.promotion_id",
need_pay: '$_id.need_pay'
},
details: {
$push: {
product_id: "$_id.product_id",
name: '$product_name',
price: '$price',
amount: '$amount',
packing: '$packing',
quantity: '$quantity'
}
}
}
}], fn);
转载于:https://www.cnblogs.com/fhen/p/5784484.html