使用猫鼬查找过去 7 天内的注册用户总数
Find total of registered user in the last 7 days using mongoose
我将我的数据存储在这样的架构中
enter image description here
我想知道如何在 mongoose 中创建查询以获取过去 7 天内创建的用户数,我希望我的输出是这样的
{
第一天:4,
第二天:4,
第三天:9,
第 4 天:12,
第五天:7,
第 6 天:0,
第 7 天:10
}
抱歉我的英语不好
const usersCount = await User.countDocuments({
created_at: { $lt: new Date('2022-04-08'), $gt: new Date('2022-04-01') }
});
这将为您提供过去 7 天内创建的用户数。您可以在快递后端生成的动态日期。
您好,我使用 mongo 聚合来对您每天需要的数据进行分组,如下所示:
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",
},
},
]);
我将我的数据存储在这样的架构中
enter image description here
我想知道如何在 mongoose 中创建查询以获取过去 7 天内创建的用户数,我希望我的输出是这样的
{ 第一天:4, 第二天:4, 第三天:9, 第 4 天:12, 第五天:7, 第 6 天:0, 第 7 天:10 }
抱歉我的英语不好
const usersCount = await User.countDocuments({
created_at: { $lt: new Date('2022-04-08'), $gt: new Date('2022-04-01') }
});
这将为您提供过去 7 天内创建的用户数。您可以在快递后端生成的动态日期。
您好,我使用 mongo 聚合来对您每天需要的数据进行分组,如下所示:
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",
},
},
]);