为比 NOW 小的日期时间值查询 MongoDB?
对此,你可以使用 $lte 操作符和新的 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") }
广告