MongoDB 中“现在”和给定日期之间的差值?
要获得 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 }
广告