Bạn có thể sử dụng toán tử $ lte cùng với Date () mới cho việc này. 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.dateTimeValueLessThanNowDemo.insertOne({"CustomerName":"Larry","CustomerProductName":"Product-1","ArrivalDate":new ISODate("2017-01-31")});
{
"acknowledged" : true,
"insertedId" : ObjectId("5ca1e8ab66324ffac2a7dc59")
}
>db.dateTimeValueLessThanNowDemo.insertOne({"CustomerName":"Mike","CustomerProductName":"Product-2","ArrivalDate":new ISODate("2019-04-01")});
{
"acknowledged" : true,
"insertedId" : ObjectId("5ca1e8c166324ffac2a7dc5a")
}
>db.dateTimeValueLessThanNowDemo.insertOne({"CustomerName":"Chris","CustomerProductName":"Product-3","ArrivalDate":new ISODate("2019-03-31")});
{
"acknowledged" : true,
"insertedId" : ObjectId("5ca1e8d266324ffac2a7dc5b")
}
>db.dateTimeValueLessThanNowDemo.insertOne({"CustomerName":"Robert","CustomerProductName":"Product-4","ArrivalDate":new ISODate("2019-04-02")});
{
"acknowledged" : true,
"insertedId" : ObjectId("5ca1e8e766324ffac2a7dc5c")
} 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.dateTimeValueLessThanNowDemo.find().pretty();
Điều này sẽ tạo ra kết quả sau
{
"_id" : ObjectId("5ca1e8c166324ffac2a7dc5a"),
"CustomerName" : "Mike",
"CustomerProductName" : "Product-2",
"ArrivalDate" : ISODate("2019-04-01T00:00:00Z")
}
{
"_id" : ObjectId("5ca1e8d266324ffac2a7dc5b"),
"CustomerName" : "Chris",
"CustomerProductName" : "Product-3",
"ArrivalDate" : ISODate("2019-03-31T00:00:00Z")
}
{
"_id" : ObjectId("5ca1e8e766324ffac2a7dc5c"),
"CustomerName" : "Robert",
"CustomerProductName" : "Product-4",
"ArrivalDate" : ISODate("2019-04-02T00:00:00Z")
} Sau đây là truy vấn cho giá trị ngày giờ nhỏ hơn NOW. Giả sử ngày hiện tại là 2019-04-02
> db.dateTimeValueLessThanNowDemo.find({ ArrivalDate: { $lte: new Date() } }).pretty(); Điều này sẽ tạo ra kết quả sau
{
"_id" : ObjectId("5ca1e8ab66324ffac2a7dc59"),
"CustomerName" : "Larry",
"CustomerProductName" : "Product-1",
"ArrivalDate" : ISODate("2017-01-31T00:00:00Z")
}
{
"_id" : ObjectId("5ca1e8c166324ffac2a7dc5a"),
"CustomerName" : "Mike",
"CustomerProductName" : "Product-2",
"ArrivalDate" : ISODate("2019-04-01T00:00:00Z")
}
{
"_id" : ObjectId("5ca1e8d266324ffac2a7dc5b"),
"CustomerName" : "Chris",
"CustomerProductName" : "Product-3",
"ArrivalDate" : ISODate("2019-03-31T00:00:00Z")
}