要计算时间戳差异,请使用聚合框架。首先让我们创建一个包含文档的集合-
> db.timestampDifferenceDemo.insertOne({ "MovieBeginningTime": new ISODate("2019-05-12 10:20:30"), "MovieEndingTime":new ISODate("2019-05-12 12:30:20") }); { "acknowledged" : true, "insertedId" : ObjectId("5cd7ba1f6d78f205348bc644") } > db.timestampDifferenceDemo.insertOne({ "MovieBeginningTime": new ISODate("2019-05-12 04:00:00"), "MovieEndingTime":new ISODate("2019-05-12 07:10:00") }); { "acknowledged" : true, "insertedId" : ObjectId("5cd7ba3b6d78f205348bc645") }
以下是在find()
方法的帮助下显示集合中所有文档的查询-
> db.timestampDifferenceDemo.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5cd7ba1f6d78f205348bc644"), "MovieBeginningTime" : ISODate("2019-05-12T10:20:30Z"), "MovieEndingTime" : ISODate("2019-05-12T12:30:20Z") } { "_id" : ObjectId("5cd7ba3b6d78f205348bc645"), "MovieBeginningTime" : ISODate("2019-05-12T04:00:00Z"), "MovieEndingTime" : ISODate("2019-05-12T07:10:00Z") }
以下是计算MongoDB中时间戳差异的查询(以小时为单位)-
> db.timestampDifferenceDemo.aggregate([ {$project: { DifferenceInHours: {$divide: [{$subtract: ["$MovieEndingTime", "$MovieBeginningTime"]}, 3600000]} }} ]);
这将产生以下输出-
{ "_id" : ObjectId("5cd7ba1f6d78f205348bc644"), "DifferenceInHours" : 2.1638888888888888 } { "_id" : ObjectId("5cd7ba3b6d78f205348bc645"), "DifferenceInHours" : 3.1666666666666665 }