我无法使用Node.js访问mongodb .db数据中的数组



我无法到达mongodb .db中orders集合中数据的第二行中数组的第二个元素并获得它们的总数。我使用Node.js。我想要得到"数量"最近两个月的总金额。

const getMonthlySales = asyncHandler(async (req, res) => {
`const quantity = req.query.pid;
const date = new Date();
const lastMonth = new Date(date.setMonth(date.getMonth() - 1));
const previousMonth = new Date(new Date().setMonth(lastMonth.getMonth() - 1));

if (req.user.isAdmin) {

try {
const sales = await OrderController.aggregate([
{
$match: {
createdAt: {$gte: previousMonth}, ...(quantity && {
products: {$elemMatch: {quantity}},
})`your text`
}
},
{
$project: {
month: {$month: "$createdAt"},
sales: "$quantity",
},
},
{
$group: {
_id: "$month",
total: {$sum: "$sales"},
},
},
]);
`
console.log(sales)
res.status(200).json(sales);
} catch (err) {
res.status(500).json(err);
}
} else {
res.status(403).json("You are not allowed to see monthly income!");
}
});

my data:

_id:ObjectId('6373f7502659c534b4f82d2f')
userId:"6373f3152659c534b4f82c67"
products:Array
0:Object
productId:"636792b261e41fa0b30d64d0"
quantity:3
_id:ObjectId("6373f7502659c534b4f82d30")
1:Object
productId:"636792b261e41fa0b30d64d0"
quantity:3
_id:ObjectId("6373f7502659c534b4f82d30")
amount:300
address:"NY"
status:""
createdAt:2022-10-15T20:32:16.675+00:00
updatedAt:2022-10-15T20:32:16.675+00:00
__v:0

id:ObjectId('6373f7502659c534b4f82d2f')
userId:"6373f3152659c534b4f82c67"
products:Array
products:Array
0:Object
productId:"636792b261e41fa0b30d64d0"
quantity:2
_id:ObjectId("6373f7502659c534b4f82d30")
1:Object
productId:"636792b261e41fa0b30d64d0"
quantity:2
_id:ObjectId("6373f7502659c534b4f82d30")
amount:300
address:"NY"
status:""
createdAt:2022-11-15T20:32:16.675+00:00
updatedAt:2022-11-15T20:32:16.675+00:00
__v:0

i expected to happen:[{_id: 10, total: 6}, {_id: 11, total: 4}]结果是:[{_id: 10、总:0},{_id: 11日总:0}]

在product数组上使用$unwind,那么总数将根据需要出现。所示:

db.collection.aggregate([
{
"$unwind": "$products"
},
{
"$group": {
_id: {
"$month": "$createdAt"
},
total: {
"$sum": "$products.quantity"
}
}
}
])

https://mongoplayground.net/p/nb_1gu5pUjm

最新更新