我正在聚合以對Orders物件執行一些分析,我想從上個月的每個訂單中獲取總價格,以及從本月開始的總價格,我嘗試$match使用適當的時間條件傳入引數,但它不是聚合任何資料。即使我countDocuments使用相同的時間條件執行查詢,我也會回傳許多檔案。
const totalThis = await Order.aggregate([
{
$match: {
// should cut the amount of orders off at the beginning of the current month
createdAt: { $gte: thisMonth.getMonth() 1 },
},
},
{
$group: {
// using $group, _id has to be there or it doesnt
// return anything, though we dont need an _id
_id: null,
total: {
$sum: "$totalPrice",
},
},
},
]);
res.status(200).json({
lastMonth: lastMonthSales,
thisMonth: thisMonthSales,
totalSalesLast: totalLast,
totalSalesThis: totalThis,
});
在我的 Postman 請求中,回傳 0,因此回傳的陣列為空是lastMonth有意義的,但回傳 5 個檔案,所以它應該可以作業。顯然,如果我洗掉條件,它將聚合所有檔案,但那是因為它正在處理所有檔案而不是實際過濾。totalSalesLastthisMonth$match
uj5u.com熱心網友回復:
要查詢createdAt特定月份的檔案,您的$match階段應如下所示:
$month- 從 中獲取月份值createdAt。$eq- 比較 (1) 中的月份和輸入月份是否相同。
{
$match: {
$expr: {
$eq: [
{
"$month": "$createdAt"
},
thisMonth.getMonth() 1
]
}
}
}
示例 Mongo Playground
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/433610.html
上一篇:MongoDB-dateAsString回傳[objectobject]
下一篇:連接前端和后端
