Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/37.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 如何使用日期字段按周、小时和天筛选文档_Node.js_Mongodb_Express_Mongoose - Fatal编程技术网

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

Node.js 如何使用日期字段按周、小时和天筛选文档,node.js,mongodb,express,mongoose,Node.js,Mongodb,Express,Mongoose,我是express和mongoDB的初学者。我在做一个任务,我有一个叫做“销售”的模型- { userName : String, amount : Number, date : Date } 现在我必须创建一个API,它应该有3种类型的参数——“每日”、“每周”、“每月”。 如果参数为 每天-然后我必须根据每天每小时的销售表发送统计数据(金额总和) 每周-然后我必须根据一周中的每一天发送统计数据 每月-然后我必须发送每月每天的统计数据 在考虑了一些逻辑之后

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

{
    userName : String,
    amount   : Number,
    date     : Date
}
现在我必须创建一个API,它应该有3种类型的参数——“每日”、“每周”、“每月”。 如果参数为

每天-然后我必须根据每天每小时的销售表发送统计数据(金额总和)

每周-然后我必须根据一周中的每一天发送统计数据

每月-然后我必须发送每月每天的统计数据

在考虑了一些逻辑之后,我想到了这个-

我可以做每日统计,但它看起来也很复杂

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);
    }
})
我想要的一些输出结构-用于每日

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

你知道我如何处理这个问题吗?

你可以根据输入构建查询条件,但让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
    }
]

您似乎总是在查询整个集合,这是您的预期行为吗?或者对于“每日”查询,您只需要过去24小时的文档?如果您可以添加输出结构示例,这也会很有帮助,因为当前代码的输出让我感到困惑。@TomSlabbaert这是预期的行为。我必须返回所有三个文档的统计数据cases@TomSlabbaert添加了一个结构化的输出示例,希望可以清除一些内容?@Tomslabaert like wise in weekly它将用于周一、周二,。。。星期天。(对于所有的星期一)和每月{每月的第1天:(对所有的文档求和每月的第1天金额)}我会试试这个,我编辑了我的问题,为我如何完成每日任务添加了逻辑。也许这可以帮助你理解我想要什么?那么小时组是基于特定日期的特定小时,而不是所有日期的所有相同“小时”?我将编辑我的答案以反映这一点,我想我可以从你的答案中得到我想要的。感谢用更多代码编辑的洛蒂,以反映我认为你想要的。你是对的,我有一个语法错误,我修正了。
[
    {
        _id: { year: 2020, month: 5, week: 13, day: 22, hour: 5},
         sum: 50
    }
]