查询MongoDB的日期时间值是否小于NOW?

您可以将$lte运算符与new一起使用Date()。首先让我们创建一个包含文档的集合

>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")
}

以下是在find()方法的帮助下显示集合中所有文档的查询

> db.dateTimeValueLessThanNowDemo.find().pretty();

这将产生以下输出

{
   "_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")
}

以下是查询日期时间值小于NOW的值。假设当前日期为2019-04-02

> db.dateTimeValueLessThanNowDemo.find({ ArrivalDate: { $lte: new Date() } }).pretty();

这将产生以下输出

{
   "_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")
}