MongoDB聚合框架 - 按年分组 [英] MongoDB Aggregate Framework - Group by Year
问题描述
我一直在尝试使用聚合函数按年份对日期字段进行分组:
I've been trying to use the aggregate function to group date fields by year:
db.identities.aggregate([
{
$group : {
_id : { year : {$year : "$birth_date"}},
total : {$sum : 1}
}
}
])
然而我的一些日期在1970年之前下降作为Windows用户,我得到一个关于gmtime的令人讨厌的错误:
Some of my dates however fall before 1970 and being a Windows user I get a nasty error about gmtime:
{
"errmsg" : "exception: gmtime failed - your system doesn't support dates before 1970",
"code" : 16422,
"ok" : 0
}
我知道现在显而易见的答案是让我运行虚拟机或其他东西,但我很好奇是否有任何针对Windows的解决方案(Windows 7 in我的情况)。如果没有多少性能影响将日期存储为嵌套对象,那就是:
I know the obvious answer now is for me to get a virtual machine running or something but I was just curious if there were any work-arounds for windows (Windows 7 in my case). Failing that how much of a performance hit would storing the date as a nested object be i.e:
birth_date : {
year : 1980,
month : 12,
day : 9
}
我不太确定索引等会有多忙。
I'm not too sure how hectic that would be with indexes etc.
任何建议都值得赞赏!
推荐答案
已知某些版本的Windows可以正常工作。你有没有机会使用32位操作系统?有问题的代码是这里,取决于 gmtime_s()
实现。
Some versions of Windows have been known to work. By any chance, are you using a 32-bit OS? The code in question is here, and depends upon the gmtime_s()
implementation.
如果此集合仅用于聚合查询,则可以将日期组件存储在对象中。我建议缩写字段名称(例如 y
, m
, d
)保存存储,因为字段字符串存在于每个存储的文档中。这里的权衡是不能使用任何聚合日期运算符。您可能希望将时间戳存储为有符号整数(例如 ts
),以便在必要时可以轻松地进行范围查询。
If this collection is simply for aggregation queries, you can certainly get by with storing date components in an object. I'd suggest abbreviating the field names (e.g. y
, m
, d
) to save on storage, since the field strings are present in each stored document. The trade-off here is that none of the aggregation date operators can be used. You may want to store the timestamp as a signed integer (e.g. ts
) so that you can easily do range queries if necessary.
这篇关于MongoDB聚合框架 - 按年分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!