我有一个名为Document in MongoDB的集合.此集合中的文档具有以ISO日期类型存储的名为CreationDate的字段.我的任务是计算每天创建的文档数量,并按异步数量排序.输出格式必须是[{_id:'yyyy-MM-dd',cnt:x}].我尝试使用如下聚合框架.
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}}
);
Run Code Online (Sandbox Code Playgroud)
代码给出了如下错误:
$concat only supports strings, not NumberInt32
Run Code Online (Sandbox Code Playgroud)
我明白这是因为$ year,$ month和$ dayOfMonth都返回了数字.可以将_id字段组合为对象,并在应用程序级别以所需格式重新格式化它.
但从技术角度来看,我有两个问题:
如何在MongoDB shell中将数字转换为字符串?在这种情况下,$ year的输出可以转换为字符串并在$ concat中使用.
有没有更好的方法将ISODate输出格式化为各种日期格式?在许多情况下,我们只需要ISODate的某些部分,例如:日期组件或时间部分.是否有任何MongoDb内置运营商来实现这一目标?
提前感谢任何建议.
是否有一个我可以在聚合函数中使用的运算符来获取字符串而不是ObjectId作为响应?
db.something.aggregate([ {$match: {'property': {$exists:true}} }, {$project: {stringId: '$_id.???'}}])
Run Code Online (Sandbox Code Playgroud)