要获得MongpDB中日期之间的时差,请使用aggregate()。让我们创建一个包含文档的集合-
> db.demo734.insertOne({GivenDate:new ISODate("2020-01-10")}); { "acknowledged" : true, "insertedId" : ObjectId("5ead4f1a57bb72a10bcf064e") } > db.demo734.insertOne({GivenDate:new ISODate("2020-02-20")}); { "acknowledged" : true, "insertedId" : ObjectId("5ead4f2157bb72a10bcf064f") } > db.demo734.insertOne({GivenDate:new ISODate("2010-12-01")}); { "acknowledged" : true, "insertedId" : ObjectId("5ead4f2b57bb72a10bcf0650") } > db.demo734.insertOne({GivenDate:new ISODate("2020-05-01")}); { "acknowledged" : true, "insertedId" : ObjectId("5ead506f57bb72a10bcf0651") }
在find()方法的帮助下显示集合中的所有文档-
> db.demo734.find();
这将产生以下输出-
{ "_id" : ObjectId("5ead4f1a57bb72a10bcf064e"), "GivenDate" : ISODate("2020-01-10T00:00:00Z") } { "_id" : ObjectId("5ead4f2157bb72a10bcf064f"), "GivenDate" : ISODate("2020-02-20T00:00:00Z") } { "_id" : ObjectId("5ead4f2b57bb72a10bcf0650"), "GivenDate" : ISODate("2010-12-01T00:00:00Z") } { "_id" : ObjectId("5ead506f57bb72a10bcf0651"), "GivenDate" : ISODate("2020-05-01T00:00:00Z") }
以下是查询以获取“现在”和给定日期之间的时差-
> db.demo734.aggregate([ ... {$project: { ... ... "differenceMilli": { ... ... $subtract:[ ... new ISODate(), ... "$GivenDate" ... ] ... } ... } ... }, ... {$project: { ... ... "differenceMilli": 1, ... "differenceindays": { ... $divide: [ ... "$differenceMilli", ... 1000 * 60 * 60 * 24 ... ] ... } ... } ... }] ... )
这将产生以下输出-
{ "_id" : ObjectId("5ead4f1a57bb72a10bcf064e"), "differenceMilli" : NumberLong("9802234864"), "differenceindays" : 113.45179240740741 } { "_id" : ObjectId("5ead4f2157bb72a10bcf064f"), "differenceMilli" : NumberLong("6259834864"), "differenceindays" : 72.45179240740741 } { "_id" : ObjectId("5ead4f2b57bb72a10bcf0650"), "differenceMilli" : NumberLong("297255034864"), "differenceindays" : 3440.4517924074075 } { "_id" : ObjectId("5ead506f57bb72a10bcf0651"), "differenceMilli" : NumberLong(125434864), "differenceindays" : 1.4517924074074073 }