Đầu tiên, lấy tháng hiện tại và trừ đi 1 để tìm nạp các bản ghi của tháng trước. Trước tiên, hãy để chúng tôi tạo một bộ sưu tập với các tài liệu -
> 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")
} Sau đây là truy vấn để hiển thị tất cả các tài liệu từ một bộ sưu tập với sự trợ giúp của phương thức find () -
> db.findOneMonthAgoData.find();
Điều này sẽ tạo ra kết quả sau -
{ "_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") } Đây là truy vấn để lấy kết quả từ tháng trước -
> monthData=new Date();
ISODate("2019-12-26T16:43:04.283Z")
> monthData.setMonth(monthData.getMonth() - 1);
1574786584283
> db.findOneMonthAgoData.find({PurchaseDate:{$gte:monthData}}); Điều này sẽ tạo ra kết quả sau -
{ "_id" : ObjectId("5e04e16c150ee0e76c06a04f"), "CustomerName" : "Chris", "PurchaseDate" : ISODate("2019-12-26T00:00:00Z") }
{ "_id" : ObjectId("5e04e186150ee0e76c06a051"), "CustomerName" : "Bob", "PurchaseDate" : ISODate("2020-11-26T00:00:00Z") }