问题
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 }
}
}
]
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
)
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.
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.
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 inproject
stage.
回答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"
]
}}
来源:https://stackoverflow.com/questions/51188337/mongo-aggregation-convert-string-to-date-in-version-3-4-7