[问题]

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. BZOJ3286 Fibonacci矩阵 矩阵 快速幂 卡常

    欢迎访问~原文出处——博客园-zhouzhendong 去博客园看该题解 题目传送门 - BZOJ3286 题意概括 n,m,a,b,c,d,e,f<=10^1000000 题解 神奇的卡常题目 ...

  2. 044 hive与mysql两种数据源之间的join

    这篇文章是基于上一篇文章的续集 一:需求 1.图形表示 二:程序 1.程序. package com.scala.it import java.util.Properties import org.a ...

  3. 五种UML工具

    ProcessOn是一款在线流程图软件(https://www.processon.com/),能够高效的完成在线流程图.UI原型图.UML以及组织图,网络拓扑图的构建.该软件最大的特点是,无需安装, ...

  4. 使用 PySide2 开发 Maya 插件系列 总览

    使用 PySide2 开发 Maya 插件系列 总览 使用 PySide2 开发 Maya 插件系列一:QT Designer 设计GUI, pyside-uic 把 .ui 文件转为 .py 文件 ...

  5. 2018年中国研究生数学建模竞赛C题 二等奖 赛题论文

    2018年中国研究生数学建模竞赛C题 对恐怖袭击事件记录数据的量化分析 恐怖袭击是指极端分子或组织人为制造的.针对但不仅限于平民及民用设施的.不符合国际道义的攻击行为,它不仅具有极大的杀伤性与破坏力, ...

  6. poj 3368 Frequent values(经典)【RMQ】

    <题目链接> 题目大意: 给你一个长度为n的序列,这个序列每个数都有一个值,接下来进行q次询问,问在指定区间内出现次数最多的数出现了几次. 解题分析: 因为该序列是非降序的,所以该序列中的 ...

  7. linux 学习笔记五 查看文件篇章

    1 diff -y  test.txt  test2.txt 输出源文件与目标文件的全部 分为左右两篮 如下 --------------------------------------------- ...

  8. 11.6 正睿停课训练 Day17

    目录 2018.11.6 正睿停课训练 Day17 A chinese(思路 计数) B physics(单调队列/剪枝 DP) C chemistry(期望 DP) 考试代码 A B C 2018. ...

  9. JavaScript基础笔记(十三)测试和调试

    错误处理与测试 一.错误处理 一)try-catch语句 function atest() { try { //可能发生错误的代码 return 0; } catch (error) { //错误处理 ...

  10. [ONTAK2015]Związek Harcerstwa Bajtockiego

    [ONTAK2015]Związek Harcerstwa Bajtockiego 题目大意: 一棵\(n(n\le10^6)\)个点的树,从\(m\)出发,依次执行\(k(k\le10^6)\)条操 ...