问题描述
我正在使用 express js 和 mongoose,而且我是这些平台的新手。如果有人可以帮助我,那就太好了。请参考以下数据,我正在寻找如下输出:
itemsizeId: 609578ca23033e55886e7590,AvailableQuantity: 112
itemsizeId: 609578ca23033e55886e758f,AvailableQuantity: 495
注意:按移动类型(向内/向外)分组。
可用库存:向内 - 向外
[
{
_id: '609fb1a1a7ed990f30d6cae2',refId: 'Purchase-1',itemsizeId: '609578ca23033e55886e7590',itemId: '609578ca23033e55886e758e',sizeId: '60950c0ba4982390f8dfed79',movementdate: '2021-05-15T11:33:52.894Z',movementtype: 'inward',movementcategory: 'purchase',quantity: 100,id: '609fb1a1a7ed990f30d6cae2',},{
_id: '609fb1cba7ed990f30d6cae3',refId: 'Purchase-2',movementdate: '2021-05-15T11:34:35.118Z',quantity: 20,id: '609fb1cba7ed990f30d6cae3',{
_id: '609fb1fda7ed990f30d6cae4',refId: 'Sale-1',movementdate: '2021-05-15T11:35:25.068Z',movementtype: 'outward',movementcategory: 'sales',quantity: 5,id: '609fb1fda7ed990f30d6cae4',{
_id: '609fb255a7ed990f30d6cae5',refId: 'Purchase-3',itemsizeId: '609578ca23033e55886e758f',sizeId: '60950be9a4982390f8dfed78',movementdate: '2021-05-15T11:36:53.835Z',quantity: 500,id: '609fb255a7ed990f30d6cae5',{
_id: '609fb27ea7ed990f30d6cae6',refId: 'Sale-2',movementdate: '2021-05-15T11:37:34.066Z',quantity: 8,id: '609fb27ea7ed990f30d6cae6',]
我一直尝试到下面的代码,我很高兴完成它:
const itemStock = await itemStockMovementModel.aggregate([
{
$match: { movementtype: 'inward' },{
$group: {
_id: {
itemsizeId: '$itemsizeId',quantity: { $sum: '$quantity' },])
解决方法
-
$group
byitemsizeId
并按条件获取inward
和outward
的数量总和 -
$subtract
到inward
-outward
const itemStock = await itemStockMovementModel.aggregate([
{
$group: {
_id: "$itemsizeId",inward: {
$sum: { $cond: [{ $eq: ["$movementtype","inward"] },"$quantity",0] }
},outward: {
$sum: { $cond: [{ $eq: ["$movementtype","outward"] },0] }
}
}
},{
$project: {
quantity: {
$subtract: ["$inward","$outward"]
}
}
}
])
如果 movementtype
中没有第三种类型,您也可以使用第二个公式,
-
$group
byitemsizeId
- 如果
movementtype
为inward
,则检查条件,则求和quantity
否则求和为负quantity
const itemStock = await itemStockMovementModel.aggregate([
{
$group: {
_id: "$itemsizeId",quantity: {
$sum: {
$cond: [
{ $eq: ["$movementtype",{ $subtract: [0,"$quantity"] }
]
}
}
}
}
])