[问题]

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

Data type conversion in MongoDB的更多相关文章

  1. java 反射 报错:Attempt to get java.lang.Integer field "..." with illegal data type conversion to int

    类: Integer id; 反射时: Field f = User.class.getDeclaredField("id"); f.setAccessible(true); in ...

  2. 【你吐吧c#每日学习】11.10 C# Data Type conversion

    implicit explicit float f=12123456.213F int a = Convert.ToInt32(f); //throw exception or int a = (in ...

  3. PythonStudy——数据类型转化 Data type conversion

    类型转换 1.数字类型:int() | bool() | float() 2.str与int:int('10') | int('-10') | int('0') | float('-.5') | fl ...

  4. The conversion of a varchar data type to a datetime data type resulted in an out-of-range value

    刚刚有在程序中,传递一个空值至MS SQL Server数据库,这个值的数据类型为DATETIME执行时,它却发生了如标题提示的异常:The conversion of a varchar data ...

  5. Spring Framework 官方文档学习(四)之Validation、Data Binding、Type Conversion(一)

    题外话:本篇是对之前那篇的重排版.并拆分成两篇,免得没了看的兴趣. 前言 在Spring Framework官方文档中,这三者是放到一起讲的,但没有解释为什么放到一起.大概是默认了读者都是有相关经验的 ...

  6. Spring Framework 官方文档学习(四)之Validation、Data Binding、Type Conversion(二)

    接前一篇 Spring Framework 官方文档学习(四)之Validation.Data Binding.Type Conversion(一) 本篇主要内容:Spring Type Conver ...

  7. Spring Framework 官方文档学习(四)之Validation、Data Binding、Type Conversion

    本篇太乱,请移步: Spring Framework 官方文档学习(四)之Validation.Data Binding.Type Conversion(一) 写了删删了写,反复几次,对自己的描述很不 ...

  8. SQL Server发布订阅报错:The conversion of a datetime data type to smalldatetime data type resulted in an out of range value.

    执行SQL Server发布订阅时,报错如下信息: The conversion of a datetime data type to smalldatetime data type resulted ...

  9. JavaScript Type Conversion

    Data Types 5 Data Types string, number, boolean, object, function 3 Object Types object, array, date ...

随机推荐

  1. 如何删除github里面的项目

    第一步 :首先登陆github 第二步:如下图选择 第三步:选择如下图 第四步:点击你要删除的项目,点击settings 第五步:把页面向下拉,找到如图按钮并点击 第六步:需要确认输入你要删除的项目名 ...

  2. linux中通过lsof恢复删除的文件,前题是fd被占用。

    http://www.serverwatch.com/tutorials/article.php/3822816/Recovering-Deleted-Files-With-lsof.htm One ...

  3. 029 c3p0的小测试

    今天被问到这个问题,就实验了一下,后续会继续补充一些配置项的意思. 一:操作步骤 1.大纲 2.新建sql -- ---------------------------- -- Table struc ...

  4. CodeSignal 刷题 —— matrixElementSum

    After they became famous, the CodeBots all decided to move to a new building and live together. The ...

  5. oracle中计算百分比,并同时解决小数点前0不显示的问题

    select a.catalog_name,decode(substr(trunc((a.s/b.count2),4)*100||'%',0,1),'.',replace(trunc((a.s/b.c ...

  6. datatables后端分页

    0x01 缘由 平时较少涉及前端,这次本以为模板中有表单,分页跳转搜索功能都比较齐全,可以高枕无忧,但是细看模板中的分页跳转是不需要与后台交互的,数据一次性写在前端,再有前端插件完成分页. 这种方式肯 ...

  7. vue cli3.0 结合echarts3.0和地图的使用方法

    echarts 提供了直观,交互丰富,可高度个性化定制的数据可视化图表.而vue更合适操纵数据. 最近一直忙着搬家,就没有更新博客,今天抽出空来写一篇关于vue和echarts的博客.下面是结合地图的 ...

  8. spring_AOP_XML

    例子下载 对于xml的AOP配置主要集中在配置文件中,所以只要设置好配置文件就行了 beans.xml <?xml version="1.0" encoding=" ...

  9. 【RAY TRACING THE REST OF YOUR LIFE 超详解】 光线追踪 3-6 直接光源采样

    Chapter7 Sample Lights Directly  Preface 今天我们来讲这个还算牛逼的技术——直接光源采样 之前我们提到过,在2-7 前两篇我们也提到要减少噪点,就是图片上的黑点 ...

  10. [LOJ6356]四色灯

    [LOJ6356]四色灯 题目大意: 有\(n(n\le10^9)\)个编号\(1\sim n\)的格子和\(m(m\le20)\)个按钮.每个格子有一个初始为\(0\)的数,每个按钮有一个数字\(a ...