计算 MongoDB 中 2 次之间的差异 [英] Calculate difference between 2 times in MongoDB

查看:37
本文介绍了计算 MongoDB 中 2 次之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 Last Modified At 的字段,其值类似于2016/04/12 20:24:18".它不是 ISO 日期,而是通过 Java 进程存储在 MongoDb 中的普通字符串值.我正在尝试编写一个 shell 脚本来计算2016/04/12 20:24:18"和2016/04/12 16:24:18"之间的差异.差异可能以天或小时或分钟或秒为单位.我尝试了几件事,包括转换为 ISO 日期,但没有成功.有没有像 Oracle 一样的简单方法来查找.

I have a field called Last Modified At with value like '2016/04/12 20:24:18'. It is not an ISO Date but a normal String value stored via a java process in MongoDb. I am trying to write a shell script to calculate the difference between '2016/04/12 20:24:18' and say '2016/04/12 16:24:18'. The difference could be either in days or hours or mins or secs. I tried couple of things including converting to ISO dates but it doesnt work out. Is there an easy way to find out like Oracle.

任何帮助将不胜感激?

谢谢,拉姆

推荐答案

我不太确定您打算如何运行 shell 脚本,但是在 mongo shell 中可以解析日期(使用 Javascript)并计算时间在您要求的两个日期之间.假设我们在 things 数据库中有一个文档如下:

I'm not exactly sure how you plan on running the shell script, but it is possible in the mongo shell to parse dates (using Javascript) and calculate time between two dates as you have asked. Assume we have a document in the things database as follows:

{
    "_id" : ObjectId("570f1e528163383227ace761"),
    "lastModifiedAt" : "2016/04/12 20:24:18"
}

我们可以运行以下脚本来获取文档的lastModifiedDate和硬编码日期之间的差异,例如2016/04/12 16:24:18:

We can run the following script to get the difference between the lastModifiedDate of a document and a hard-coded date, such as 2016/04/12 16:24:18:

db.things.find({}).forEach(function(thing) {
    var date1 = new Date(thing.lastModifiedAt);
    var date2 = new Date('2016/04/12 16:24:18');
    var dateDiff = date1.getTime() - date2.getTime();
    printjson({_id:thing._id,lastModifiedAt:thing.lastModifiedAt,dateDiff:dateDiff});
});

结果:

{
    "_id" : ObjectId("570f1e528163383227ace761"),
    "lastModifiedAt" : "2016/04/12 20:24:18",
    "dateDiff" : 14400000
}

其中 dateDiff 是毫秒,14400000 毫秒 = 4 小时.

如果您提供有关您计划如何拨打此电话的更多信息,以及第二次约会的地点,我很乐意对此答案进行扩展.

If you provide more information on how you plan on making this call, and where the second date is coming from I would be happy to expand upon this answer.

这篇关于计算 MongoDB 中 2 次之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆