Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
315 views
in Technique[技术] by (71.8m points)

javascript - 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}
        }
    }   
])

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
}

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.

Any advice appreciated!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...