Mongo Aggregation在3.4.7版中将字符串转换为日期

编程入门 行业动态 更新时间:2024-10-26 10:32:00
本文介绍了Mongo Aggregation在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版中将字符串转换为日期

    本文发布于:2023-11-16 06:18:01,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1601749.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:转换为   字符串   版中   日期   Mongo

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!