gpt4 book ai didi

node.js - 使用 Mongoose 查找过去 7 天内的注册用户总数

转载 作者:行者123 更新时间:2023-12-05 05:43:34 26 4
gpt4 key购买 nike

我将我的数据存储在这样的模式中

enter image description here

我想知道如何在 mongoose 中创建查询以获取过去 7 天内创建的用户数,我希望我的输出是这样的

{第一天:4,第二天:4,第三天:9,第 4 天:12,第五天:7,第 6 天:0,第 7 天:10

抱歉我的英语不好

最佳答案

您好,我使用 mongo aggregate 对您每天需要的数据进行分组,如下所示:

const toDate = new Date("2022-04-08");

const fromDate = new Date("2022-04-01");

const data = await User.aggregate([{
$match: {
createdAt: {
$gte: new Date(fromDate),
$lte: new Date(toDate),
},
},
},
{
$sort: {
createdAt: -1
}
},
{
$project: {
day: {
$dayOfMonth: "$createdAt"
},
month: {
$month: "$createdAt"
},
year: {
$year: "$createdAt"
},
},
},
{
$group: {
_id: {
day: "$day",
year: "$year",
month: "$month",
},
count: {
$sum: 1
},
},
},
{
$project: {
_id: 0,
day: "$_id.day",
month: "$_id.month",
year: "$_id.year",
count: "$count",
},
},
]);

关于node.js - 使用 Mongoose 查找过去 7 天内的注册用户总数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71799002/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com