简体   繁体   English

计算MongoDB中2次之间的差异

[英]Calculate difference between 2 times in MongoDB

I have a field called Last Modified At with value like '2016/04/12 20:24:18'. 我有一个名为“ Last Modified At”的字段,其值类似于“ 2016/04/12 20:24:18”。 It is not an ISO Date but a normal String value stored via a java process in MongoDb. 它不是ISO日期,而是通过Java进程存储在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'. 我正在尝试编写一个shell脚本来计算'2016/04/12 20:24:18'和说'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. 我尝试了几件事,包括转换为ISO日期,但没有成功。 Is there an easy way to find out like Oracle. 有没有一种简单的方法可以找到像Oracle这样的数据库。

Any help would be appreciated? 任何帮助,将不胜感激?

Thanks, Ram 谢谢,拉姆

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. 我不确定您如何计划运行shell脚本,但是可以在mongo shell中解析日期(使用Javascript)并根据您的要求计算两个日期之间的时间。 Assume we have a document in the things database as follows: 假设在things数据库中有一个文档,如下所示:

{
    "_id" : ObjectId("570f1e528163383227ace761"),
    "lastModifiedAt" : "2016/04/12 20: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 : 我们可以运行以下脚本来获取文档的lastModifiedDate和硬编码日期之间的差异,例如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});
});

This results in: 结果是:

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

where dateDiff is milliseconds and 14400000 milliseconds = 4 hours . 其中dateDiff是毫秒, 14400000 milliseconds = 4 hours

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. 如果您提供有关如何计划拨打此电话以及第二次约会来自何方的更多信息,我将很乐意扩展此答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM