[问题]

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. Quratz的理解

    一:公共术语 1.为什么使用Qurztz 在某一个有规律的时间点干某件事.并且时间的触发的条件可以非常复杂(比如每月最后一个工作日的17:50),复杂到需要一个专门的框架来干这个事. Quartz就是 ...

  2. day75 form 组件(对form表单进行输入值校验的一种方式)

    我们的组件是什么呢 select distinct(id,title,price) from book ORM: model.py class Book(): title=model.CharFiel ...

  3. VS项目启动后 提示ID为*******的进程当前未运行

    就是VS2015中的这种问题,启动调试时,右下角根本没有IISPress图标出现.我的工程是因为突然停电,就再也调试不了了! 解决办法: 用文本编辑器打开Web项目下的{X}.csproj文件,然后查 ...

  4. 初识Linux系统

    1. pwd 显示现在所在位置 2. ls 显示目录下的文件 ls -a:显示隐藏文件(带 . 的就是隐藏文件): ls -a -l :每个文件夹的详细信息: ls > bbb (把查到的所有文 ...

  5. java中可以对时间进行加减处理,有时候不用在sql语句中处理

    String ssny = (String) pd.get("ssny");   SimpleDateFormat simpleDateFormat=new SimpleDateF ...

  6. 64位 windows10下 Apache2.4 + php7 + phpstorm 相关设置

    64位 windows10下 Apache2.4 + php7 + phpstorm 相关设置   转  https://blog.csdn.net/laurencechan/article/deta ...

  7. getting data from the keybroad

    public static String getString() throws IOException{ InputStreamReader isr = new InoutStreamReader(S ...

  8. 【ABP】ABP跨域调用API时出现的问题

    public override void Initialize() { IocManager.RegisterAssemblyByConvention(Assembly.GetExecutingAss ...

  9. Windows上搭建安卓的Java开发环境

    下载安装JDK path的系统变量增加值(示例): D:\Program Files\Java\jdk1.8.0_25\bin同理为名为classpath的系统变量增加值(示例:没有的话可以新建)D: ...

  10. JavaScript基础笔记(六)BOM

    BOM 一.Window对象 在浏览器中window对象即是全局对象,又是JavaScript访问浏览器的一个接口. 定义全局变量和定义window对象还是有差别的,全局变量不能通过delete操作符 ...