[问题]

I have a collection called Document in MongoDB. Documents in this collection have a field called CreationDate stored in ISO date type. My task is to count the number of documents created per day and sort by the number asynchronously. The output format is required to be [{_id:'yyyy-MM-dd', cnt:x}]. I tried to use aggregation framework as below.

db.Document.aggregate(

, {$project: {_id:1, Year:{$year:'$CreationDate'}, Month:{$month:'$CreationDate'}, Date:{$dayOfMonth:'$CreationDate'}}}

, {$group: {_id:{$concat:['$Year', '-', '$Month', '-', '$Date']}, cnt:{$sum:1}}}

, {$sort:{'cnt':-1}}

);

The code gives me error as below:

$concat only supports strings, not NumberInt32

I understand this is because $year, $month and $dayOfMonth all return number. It's possible to compose the _id field as an object and re-format it in the desired format in application level.

But from technical perspective, I have two questions:

  1. How to convert a number to string in MongoDB shell? In this case, output of $year can then be converted to string and used in $concat.
  2. Is there a better way to format ISODate output to various date formats? In many cases, we only need certain part of an ISODate, for example: the date component or the time portion. Is there any MongoDb inbuilt operators to achieve this?

Thanks in advance for any advice.

[回答]

You can do this with $concat but first you need to convert to a string via $substr, also handling the double digit case:

db.Document.aggregate([ 
    { "$group": { 
        "_id":{ 
            "$concat": [
                 { "$substr": [ { "$year": "$CreationDate" }, 0, 4 ] },
                 "-",
                 { "$cond": [
                     { "$gt": [ { "$month": "$CreationDate" }, 9 ] },
                     { "$substr": [ { "$month": "$CreationDate" }, 0, 2 ] },
                     { "$concat": [
                         "0",
                         { "$substr": [ { "$month": "$CreationDate" }, 0, 1 ] },
                     ]},
                 ]},
                 "-",
                 { "$cond": [
                     { "$gt": [ { "$dayOfMonth": "$CreationDate" }, 9 ] },
                     { "$substr": [ { "$dayOfMonth": "$CreationDate" }, 0, 2 ] },
                     { "$concat": [
                         "0",
                         { "$substr": [ { "$dayOfMonth": "$CreationDate" }, 0, 1 ] },
                     ]}
                 ]}
             ]
         },
         { "cnt": { "$sum": 1 } }
    }}
    { "$sort":{ "cnt" :-1 }}
]);

Possibly better is to just use date math instead, this returns an epoch timestamp value, but it is easy to work into a date object in post processing:

db.Document.aggregate([
    { "$group": {
        "_id": {
            "$subtract": [
                { "$subtract": [ "$CreationDate", new Date("1970-01-01") ] },
                { "$mod": [
                    { "$subtract": [ "$CreationDate", new Date("1970-01-01") ] },
                    1000 * 60 * 60 * 24
                ]}
            ]
        },
        "cnt": { "$sum": 1 }
    }},
    { "$sort": { "cnt": -1 } }
])

来自: https://stackoverflow.com/questions/25176855/data-type-conversion-in-mongodb

最新文章

  1. C++ std::map
  2. come on,逆战
  3. 仿iphone日历插件(beta)
  4. 在Linux或者Unix下打开,每一行都会出多出^M这样的字符
  5. Linux下Wi-Fi的实现:wireless_tools和wpa_supplicant
  6. spring aop 使用注解方式总结
  7. bzoj2005: [Noi2010]能量采集
  8. HDU 5622 KK's Chemical DP
  9. 福州大学第十届校赛 & fzu 2128最长子串
  10. Spring之SpringMVC的RequestToViewNameTranslator(源码)分析
  11. logback生成多个不同的日志文件
  12. PA 项目创建任务
  13. AutoStartUtil【打开自启动设置界面】
  14. IOS 静态库 和 动态库
  15. python 守护进程,监控进程
  16. Determine destination location of apt-get install <package>?
  17. python 使用 matplotlib.pyplot来画柱状图和饼图
  18. Exp1 PC平台逆向破解(5)M
  19. 【转&参考】MySQL利用frm和ibd文件进行数据恢复
  20. bzoj 3306

热门文章

  1. laravel 错误 1071 Specified key was too long; max key length is 1000 bytes
  2. BZOJ2724 [Violet 6]蒲公英 分块
  3. Codeforces 1000G Two-Paths 树形动态规划 LCA
  4. POJ2676 Sudoku 舞蹈链 DLX
  5. bitset里面一些函数的用法
  6. 分享一段奇葩的DBMS_JOB书写经历
  7. python2.7安装和uwsgi
  8. 一、利用Python编写飞机大战游戏-面向对象设计思想
  9. P2415 集合求和
  10. Python中list、字典、字符串的讲解