提问者:小点点

如何使用日期字段按周、小时和天筛选文档


我是express和MongoDB的初学者。我在做一个任务,我有一个模型叫销售-

{
    userName : String,
    amount   : Number,
    date     : Date
}

现在我必须创建一个API,它应该有一个三种类型的参数-“daily”,“weekly”,“monthly”。如果参数为

每天-然后我必须发送统计(金额的总和)的基础上每一个小时的一天从销售表。

每周-然后我必须发送统计的基础上每一天的一周

每月-然后我必须发送统计数据的基础上,每月的每一天

在思考了一些逻辑之后,我想出了这个-

我能做每天的统计,但看起来也很复杂

app.get("/fetchSales/:id",async (req, res)=>{
    const { id } = req.params;
    const allSales = await sales.find({});
    const dates = [];
    for(i in allSales){
        let date = allSales[i].date.toISOString().replace('Z', '').replace('T', ''); 
        const dateFormat = dayjs(date);
        dateFormat.amount = allSales[i].amount;
        dates.push(dateFormat);
    }
    if(id === "daily") {
        const stats = {};
        for(let hour = 0; hour < 24; hour++) {
            let sum = 0
           for (x in dates) {
               if (dates[x]["$H"] === hour)  sum += dates[x].amount
           }
           stats[hour] = sum;
        }
        res.send(stats);
    }
})

但是往前走,我必须使用几个循环,这看起来不太好。我读过,也许聚合查询可以帮助我。

js给我的结构天数是-

  d {
    '$L': 'en',
    '$d': 2021-01-13T13:00:00.000Z,
    '$x': {},
    '$y': 2021,
    '$M': 0,
    '$D': 13,
    '$W': 3,
    '$H': 18,
    '$m': 30,
    '$s': 0,
    '$ms': 0,
    amount: 1700 //added on my own//
  }

我想要的一些输出结构--用于日常

{
 0: 0$,
 1: 0$,
 2: 24$,
 ...
 23: 2$
}

知道我该怎么处理这件事吗?


共1个答案

匿名用户

您可以根据输入构建查询条件,但让Mongodb完成繁重的工作:

app.get("/fetchSales/:id", async (req, res) => {
    const {id} = req.params;

    const groupCondition = {
        sum: {$sum: 1}
    };

    if (id === 'monthly') {
        groupCondition._id = {$week: '$date'};
    } else if (id === 'weekly') {
        groupCondition._id = {$dayOfMonth: '$date'};
    } else if (id === 'weekly') {
        groupCondition._id = {$hour: '$date'};
    } else {
        // can this happen? what to do here.
    }

    const allSales = await sales.aggregate([
        {
            $group: groupCondition
        },
        {
            $sort: {
                _id: 1
            }
        }
    ]);
});

请注意,这不会返回文档计数为0的天/周/小时,您将不得不通过管道或在代码中手动插入它们。

对于实际$group按完整日期而不是按特定的一般小时/天执行,应使用以下命令:

app.get("/fetchSales/:id", async (req, res) => {
    const {id} = req.params;

    const groupCondition = {
        _id: {year: {$year: '$date'}, $month: {'$month': "$date"}, week: {'$week': "$date"} },
        sum: {$sum: 1},
        date: {$first: '$date'} //for sorting
    };

    switch (id) {
        case 'weekly':
            groupCondition._id.$dayOfMonth = {$dayOfMonth: '$date'};
        case 'daily':
            groupCondition._id.$hour = {$hour: '$date'};
    }

    const allSales = await sales.aggregate([
        {
            $group: groupCondition
        },
        {
            $sort: {
                date: 1
            }
        },
        {
            $project: {
                _id: 1,
                sum: 1
            }
        }
    ]);
});

这将为您提供以下结构的文档:

[
    {
        _id: { year: 2020, month: 5, week: 13, day: 22, hour: 5},
         sum: 50
    }
]