且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

MongoDb 如何从字符串中按月份和年份分组

更新时间:2023-01-29 21:32:50

您不能在任何其他情况下使用 日期聚合运算符Date 对象本身.您最终的***选择是将这些字符串"转换为正确的 Date 对象,以便您可以在此操作和以后的操作中正确查询.

You cannot use the date aggregation operators on anything else that is tho a Date object itself. Your ultimate best option is to convert these "strings" to proper Date objects so you can query correctly in this and future operations.

也就是说,如果你的字符串"总是有一个共同的结构,那么有一种方法可以用 聚合框架 工具.它需要大量的操纵思想,但这并不能使其成为处理问题的***"方法.但是有了两位数"的集合结构和一致的分隔符,这可以通过 $substr 运算符:

That said, if your "strings" always have a common structure then there is a way to do this with the aggregation framework tools. It requires a lot of manipulation thought that does not makes this an "optimal" approach to dealing with the problem. But with a set structure of "double digits" and a consistent delimiter this is possible with the $substr operator:

db.collection.aggregate([
   { "$group": {
       "_id": {
           "year": { "$substr": [ "$dateStr", 7, 4 ] },
           "month": { "$substr": [ "$dateStr", 4, 2 ] }
       },
       "count": { "$sum": 1 }
   }}
])

因此 JavaScript 转换在聚合框架内不起作用.您始终可以根据客户端代码"评估向管道馈送"输入,但聚合过程本身不评估任何代码.就像基本的查询引擎一样,这一切都是基于数据结构"实现,使用原生运算符"指令来完成工作.

So JavaScript casting does not work inside the aggregation framework. You can always "feed" input to the pipeline based on "client code" evaluation, but the aggregation process itself does not evaluate any code. Just like the basic query engine, this is all based on a "data structure" implementation that uses "native operator" instructions to do the work.

您不能在聚合管道中将字符串转换为日期.你应该使用真正的 BSON Date对象,但如果有可以以词法顺序"呈现的一致格式,则可以使用字符串来实现.

You cannot convert strings to dates in the aggregation pipeline. You should work with real BSON Date objects, but you can do it with strings if there is a consistent format that you can present in a "lexical order".

我仍然建议您尽快将这些转换为 BSON 日期.并注意ISODate"或 UTC 值是用不同的字符串形式构造的.即:

I still suggest that you convert these to BSON Dates ASAP. And beware that the "ISODate" or UTC value is constructed with a different string form. ie:

new Date("2020-01-07")

采用yyyy-mm-dd"格式.至少对于 JavaScript 调用.

Being in "yyyy-mm-dd" format. At least for the JavaScript invocation.