获取前一个月的 MongoDB 结果\n
首先,获取当前月份并减 1 以获取上个月的记录。我们首先使用文档创建集合 -
> db.findOneMonthAgoData.insertOne({"CustomerName":"Chris","PurchaseDate":new ISODate("2019-12-26")}); { "acknowledged" : true, "insertedId" : ObjectId("5e04e16c150ee0e76c06a04f") } > db.findOneMonthAgoData.insertOne({"CustomerName":"David","PurchaseDate":new ISODate("2019-11-26")}); { "acknowledged" : true, "insertedId" : ObjectId("5e04e178150ee0e76c06a050") } > db.findOneMonthAgoData.insertOne({"CustomerName":"Bob","PurchaseDate":new ISODate("2020-11-26")}); { "acknowledged" : true, "insertedId" : ObjectId("5e04e186150ee0e76c06a051") }
下面是用 find() 方法显示集合中所有文档的查询 -
> db.findOneMonthAgoData.find();
这将产生以下输出 -
{ "_id" : ObjectId("5e04e16c150ee0e76c06a04f"), "CustomerName" : "Chris", "PurchaseDate" : ISODate("2019-12-26T00:00:00Z") } { "_id" : ObjectId("5e04e178150ee0e76c06a050"), "CustomerName" : "David", "PurchaseDate" : ISODate("2019-11-26T00:00:00Z") } { "_id" : ObjectId("5e04e186150ee0e76c06a051"), "CustomerName" : "Bob", "PurchaseDate" : ISODate("2020-11-26T00:00:00Z") }
以下是获取上个月结果的查询 -
> monthData=new Date(); ISODate("2019-12-26T16:43:04.283Z") > monthData.setMonth(monthData.getMonth() - 1); 1574786584283 > db.findOneMonthAgoData.find({PurchaseDate:{$gte:monthData}});
这将产生以下输出 -
{ "_id" : ObjectId("5e04e16c150ee0e76c06a04f"), "CustomerName" : "Chris", "PurchaseDate" : ISODate("2019-12-26T00:00:00Z") } { "_id" : ObjectId("5e04e186150ee0e76c06a051"), "CustomerName" : "Bob", "PurchaseDate" : ISODate("2020-11-26T00:00:00Z") }
广告