[问题]

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. eclipse中设置自动生成的author,date等注释

    转自:http://blog.csdn.net/zhouhong1026/article/details/38396311 转自:http://hi.baidu.com/qianjian21/blog ...

  2. P1373 小a和uim之大逃离 二维dp

    题目背景 小a和uim来到雨林中探险.突然一阵北风吹来,一片乌云从北部天边急涌过来,还伴着一道道闪电,一阵阵雷声.刹那间,狂风大作,乌云布满了天空,紧接着豆大的雨点从天空中打落下来,只见前方出现了一个 ...

  3. TF:TF下CNN实现mnist数据集预测 96%采用placeholder用法+2层C及其max_pool法+隐藏层dropout法+输出层softmax法+目标函数cross_entropy法+AdamOptimizer算法

    import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data # number 1 to 10 ...

  4. python查看对象用法

    python查看类用法: dir(object_name)

  5. sql - 递归update

    declare v_rlt ):; l_sql ); -- variable that contains a query l_c sys_refcursor; -- cursor variable(w ...

  6. .net(二)

    1.维护数据库的完整性.一致性.你喜欢用触发器还是自写业务逻辑?为什么? 答:尽可能用约束(包括CHECK.主键.唯一键.外键.非空字段)实现,这种方式的效率最好:其次用触发器,这种方式可以保证无论何 ...

  7. Python 面向对象的补充

    isinstance(obj,cls)和issubclass(sub,super) isinstance(obj,cls)检查是否obj是否是类 cls 的对象 1 class Foo(object) ...

  8. pandas 基本操作

    1.     一维数据结构Series a.   概念:Series 是pandas 的一维数据结构,有重要的两个属性 index 和values b.  初始化: 可以通过 python 的 Lis ...

  9. Redis自学笔记:3.6入门-有序集合类型

    3.6有序集合类型 3.6.1介绍 在集合类型基础上,为集合中每个元素都关联了一个分数,故可以获得 分数最高(最低)的前N个元素,可以获得指定范围内的元素等 有序集合中每个元素不同,但它们的分数却可以 ...

  10. BZOJ.3170.[TJOI2013]松鼠聚会(切比雪夫距离转曼哈顿距离)

    题目链接 将原坐标系每个点的坐标\((x,y)\)变为\((x+y,x-y)\),则原坐标系中的曼哈顿距离等于新坐标系中的切比雪夫距离. 反过来,将原坐标系每个点的坐标\((x,y)\)变为\((\f ...