在mongo查询中将iso日期转换为时间戳

编程入门 行业动态 更新时间:2024-10-27 14:28:55
本文介绍了在mongo查询中将iso日期转换为时间戳的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

这里是查询

[{$项目":{格式化日期":{"$dateToString": { "format": "%Y-%m-%d", "date": "$ceatedAt" }},"createdAtMonth": { "$month": "$ceatedAt" },评分":1}},{$ 组":{"_id": "$formattedDate",平均":{$avg":$rating"},"月": { "$first": "$createdAtMonth" },}}]

我需要时间戳中的日期.怎么做?

解决方案

使用 $subtract 算术聚合运算符,您的日期为 minuend 和 new Date("1970-01-01") 作为减数.

db.collection.aggregate({$project: { "timestamp": { $subtract: [ "$createdAt", new Date("1970-01-01") ] } }});

对于文档

{ "_id": 1, "createdAt": ISODate("2016-09-01T14:35:14.952Z") }

结果是

{ "_id": 1, "timestamp": NumberLong("1472740514952") }

如果你想同时按时间戳和(年、月、日)分组,你可以用时间戳除以一天中的毫秒数,这样它对于每一天都是唯一的(而不是每一毫秒)

db.collection.aggregate({$项目:{timestampByDay":{$楼:{$除:[{ $subtract: [ "$createdAt", new Date("1970-01-01") ] },24*60*60*1000]}},日期":$createdAt"}},{$组:{"_id": "$timestampByDay",日期":{ $first:$date"}}});

here is the query

[ { "$project": { "formattedDate": { "$dateToString": { "format": "%Y-%m-%d", "date": "$ceatedAt" } }, "createdAtMonth": { "$month": "$ceatedAt" }, "rating": 1 } }, { "$group": { "_id": "$formattedDate", "average": { "$avg": "$rating" }, "month": { "$first": "$createdAtMonth" }, } } ]

I need the date in timestamp. How to do that?

解决方案

Use $subtract arithmetic aggregation operator with your Date as minuend and new Date("1970-01-01") as subtrahend.

db.collection.aggregate( { $project: { "timestamp": { $subtract: [ "$createdAt", new Date("1970-01-01") ] } } } );

For document

{ "_id": 1, "createdAt": ISODate("2016-09-01T14:35:14.952Z") }

the result is

{ "_id": 1, "timestamp": NumberLong("1472740514952") }

If you want to group both by timestamp and (year, month, date) you can divide timestamp by the amount of milliseconds in a day, so that it will be unique for each day (and not for each millisecond)

db.collection.aggregate( { $project: { "timestampByDay": { $floor: { $divide: [ { $subtract: [ "$createdAt", new Date("1970-01-01") ] }, 24 * 60 * 60 * 1000 ] } }, "date": "$createdAt" } }, { $group: { "_id": "$timestampByDay", "date": { $first: "$date" } } } );

更多推荐

在mongo查询中将iso日期转换为时间戳

本文发布于:2023-10-19 07:19:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1506777.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   中将   日期   时间   mongo

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!