【发布时间】:2020-10-12 10:37:33
【问题描述】:
我有一个聚合管道,应该按月显示一系列库存活动,从每月的前半月到后半月。
exports.InventoryTable = asyncHandler(async (req, res, next) => {
Log.aggregate([
{
$group: {
_id: {
name: '$name',
quantity: '$quantity',
year: {$year: '$updatedAt'},
month: {$month: '$updatedAt'},
dayOfMonth: {$dayOfMonth: '$updatedAt'}
},
totalAmountSold: { $sum :'$modified_quantity' },
},
},
]).exec((err, results) => {
if (err) throw err;
res.json(results);
});
});
这是示例输出:
[
{
"_id": {
"name": "Pop",
"quantity": 58,
"year": 2020,
"month": 6,
"dayOfMonth": 21
},
"totalAmountSold": -57
},
{
"_id": {
"name": "Cement",
"quantity": 51,
"year": 2020,
"month": 6,
"dayOfMonth": 21
},
"totalAmountSold": -50
},
{
"_id": {
"name": "Washing Machine",
"quantity": 85,
"year": 2020,
"month": 6,
"dayOfMonth": 21
},
"totalAmountSold": -20
},
{
"_id": {
"name": "Pop",
"quantity": 4,
"year": 2020,
"month": 6,
"dayOfMonth": 14
},
"totalAmountSold": -15
},
{
"_id": {
"name": "Cement",
"quantity": 1,
"year": 2020,
"month": 6,
"dayOfMonth": 20
},
"totalAmountSold": -17
},
{
"_id": {
"name": "Pop",
"quantity": 24,
"year": 2020,
"month": 6,
"dayOfMonth": 8
},
"totalAmountSold": -6
}
]
我希望结果以相反的顺序显示,最早的记录位于文档的顶部。我尝试过使用 sort() 函数:
]).sort({"id":-1}).exec((err, results) => {
if (err) throw err;
res.json(results);
});
````
but the record still stays the same. on second thought, I might be applying the "sort" incorrectly. I really require help with this one.
【问题讨论】: