gpt4 book ai didi

javascript - MongoDB按日期查询组集合上周/上个月/所有NodeJS

转载 作者:行者123 更新时间:2023-12-01 02:31:11 29 4
gpt4 key购买 nike

我需要统计所有用户,上周和上个月的用户,按日期分组。

我已经尝试过

var project = {
$project:{
day: { $dayOfMonth: "$updatedAt" },
month: { $month: "$updatedAt" },
year: { $year: "$updatedAt" }
}
},
group = {
"$group": {
"_id": {
"date": "$updatedAt",
},
"count" : { "$sum" : "$1" }
}
};

db.collection.aggregate([project, group])...

我需要结果看起来像

{lastWeek: 12, lastMonth: 20, all: 102}

编辑 添加了示例 json 数据。仅包含用于测试的对象的必要属性

[{
"_id" : ObjectId("someId"),
"createdAt" : ISODate("2017-04-08T09:51:44.897Z"),
"updatedAt" : ISODate("2018-01-08T09:51:55.460Z"),
"foo1" : null
},{
"_id" : ObjectId("someId"),
"createdAt" : ISODate("2017-04-08T09:51:44.897Z"),
"updatedAt" : ISODate("2017-12-30T09:51:55.460Z"),
"foo1" : null
},{
"_id" : ObjectId("someId"),
"createdAt" : ISODate("2017-04-08T09:51:44.897Z"),
"updatedAt" : ISODate("2018-01-17T09:51:55.460Z"),
"foo1" : null
},{
"_id" : ObjectId("someId"),
"createdAt" : ISODate("2017-04-08T09:51:44.897Z"),
"updatedAt" : ISODate("2018-01-01T09:51:55.460Z"),
"foo1" : null
},{
"_id" : ObjectId("someId"),
"createdAt" : ISODate("2017-04-08T09:51:44.897Z"),
"updatedAt" : ISODate("2017-04-08T09:51:55.460Z"),
"foo1" : null
}]

最佳答案

您可以尝试以下聚合

var today = new Date();
var lastWeek = new Date();
today.setDate(today.getDate() - 7);
var lastMonthFromToday = new Date();
lastMonthFromToday.setMonth(today.getMonth() - 1);

db.col.aggregate(
{"$group":{
"_id":null,
"lastWeek":{"$sum":{"$cond":[{$and:[{"$gte":["$updatedAt",lastWeek]}, {"$lte":["$updatedAt",today]}]}, 1, 0]}},
"lastMonth":{"$sum":{"$cond":[{$and:[{"$gte":["$updatedAt",lastMonthFromToday]}, {"$lte":["$updatedAt",today]}]}, 1, 0]}},
"all":{"$sum":1}
}})

Mongo 3.4版本:

db.col.aggregate(
{"$facet":{
"lastWeek":[{"$match":{"updatedAt":{"$gte":lastWeek, "$lte":today}}},{"$count":"count"}],
"lastMonth":[{"$match":{"updatedAt":{"$gte":lastMonthFromToday, "$lte":today}}},{"$count":"count"}],
"all":[{"$count":"count"}]
}})

关于javascript - MongoDB按日期查询组集合上周/上个月/所有NodeJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48307611/

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