gpt4 book ai didi

mongodb - 蒙戈 : How to group by $week but return start date and end date of each week instead?

转载 作者:行者123 更新时间:2023-12-01 23:20:45 25 4
gpt4 key购买 nike

我正在使用 $group by $week。它返回一年中的#week,但我想要开始日期,每周的结束日期而不是

示例:

当前结果:

[{
"_id" : 20,
"averageValue" : null
},
{
"_id" : 21,
"averageValue" : 28.1875
}]

期待:

[{
"_id" : [{ start: "2021-01-01", "end": "2021-01-07" }],
"averageValue" : null
},
{
"_id" : [{ start: "2021-01-08", "end": "2021-01-14" }],
"averageValue" : 28.1875
}]

最佳答案

虽然它是可行的,但会降低代码的可读性和复杂性。

我将重写 $group 阶段以包括 yearweeks 并添加 $project 阶段根据要求格式化数据。

db.collection.aggregate([
{
"$group": {
"_id": {
"week": {
"$week": {"$subtract": ["$at", 25200000]} // <-- Changes timezone to -07:00
},
"year": {
"$year": {"$subtract": ["$at", 25200000]} // <-- Changes timezone to -07:00
},
},
// <-- Add keys to be added in group along with its logics
"averageValue": {
"$avg": "$readings.level_1"
}
},
},
{
"$project": {
"_id": {
"startDate": {
"$dateToString": {
"date": {
"$dateFromParts": {
"isoWeekYear": "$_id.year",
"isoWeek": "$_id.week"
}
},
"format": "%Y-%m-%d",
},
},
"endDate": {
"$dateToString": {
"date": {
"$add": [
{
"$dateFromParts": {
"isoWeekYear": "$_id.year",
"isoWeek": "$_id.week"
}
},
518400000,
],
},
"format": "%Y-%m-%d",
},
},
},
// <-- Add remaining keys to be projected
"averageValue": 1,
},
},
])

如果您需要解释每个阶段和使用的运算符以及我为什么使用它,请告诉我。

Mongo Playground Sample Execution

关于mongodb - 蒙戈 : How to group by $week but return start date and end date of each week instead?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68127955/

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