Mongo Aggregation在3.4.7版中将字符串转换为日期 [英] Mongo aggregation Convert string to date in version 3.4.7
问题描述
我具有以下聚合器功能,我没有直接在mongo控制台中触发。我将此聚合器作为查询字符串传递给API。我将直接对以下聚合器进行编码,并将其作为查询字符串传递给get请求。
I have the following aggregator function, which I am not firing in mongo console directly. I am passing this aggregator to an API as a query string. I will encode the following aggregator directly and pass to a get request as a query string.
[
{
"$limit": 500
},
{
"$match": {
"timestamp": {
"$gte": {
"$dte": "2017-07-01"
},
"$lt": {
"$dte": "2020-12-31"
}
}
}
},
{
"$group": {
"_id": { "$year": "$timestamp" },
"scores": { "$push": "$statement.result.score.scaled" },
"duration_seconds": { "$push": "$statement.result.duration_seconds" }
}
},
{
"$project": {
"scores": 1,
"duration_seconds": 1,
"statements_count": 1,
"semester": {
"$cond": [
{
"$lte": [
{
"$month":
{
"$dateFromString": {
"dateString": "$timestamp"
}
}
}, 6
]
}, "Jan", "July"
]
}
}
},
{
"$group": {
"_id": { "semester": "$semester", "year": { "$year": "$timestamp" } },
"avg_score": { "$avg": "$scores" },
"avg_duration": { "$avg": "$duration_seconds" },
"statements_count": { "$sum": 1 }
}
}
]
在这里,我有一个对帐单文件,它有一个时间戳
,它是一个ISO日期但采用字符串格式。我想按学期对语句进行分组(如果月份为 1-6:1月,6-12:7月
)
Here I have a statement document, it has a timestamp
that is a ISO date but in string format. I want to group the statements by semester (if month is 1-6: Jan, 6-12: July
)
这里的问题是我使用的是mongo 3.4.7,而 $ dateFromString
运算符仅在3.6以上版本中有效。所以我得到一个错误。
Here the problem is I am using mongo 3.4.7 and "$dateFromString"
operator only works in above 3.6 versions. So I am getting an error.
-
那么我如何按学期在mongo 3.4.7版本中对它进行分组?
So how can I group this by semester in mongo 3.4.7 version ?
我先按学期分组时遇到以下问题。
I am facing the following issue while grouping by semester first.
而且我的汇总不适用于按学期分组。因为我该如何先使用学期分组,然后进行项目阶段? Group阶段不支持我只能在 project
阶段使用的 $ cond
等聚合器。
And my aggregation not works for grouping by semester. Because how can I use the semester grouping first and do the project stage? Group stage is not supporting $cond
etc aggregator that I can use only in project
stage.
推荐答案
您可以尝试 $ split
运算符,并带有 $ arrayElemAt
到索引1返回月的值。
You can try $split
operator with $arrayElemAt
for index 1 to return month value.
{"semester":{
"$cond":[
{"$lte":[{"$arrayElemAt":[{"$split":["$timestamp","-"]},1]},"06"]},
"Jan",
"July"
]
}}
这篇关于Mongo Aggregation在3.4.7版中将字符串转换为日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!