如何使用 MongoDB 计算时间戳差异(以小时为单位)?
要计算时间戳差异,请使用聚合框架。我们首先使用文档创建一个集合 -
> 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 }
广告