您可以与此同时使用$lte运算符Date()
。首先让我们创建一个包含文档的集合。在这里,我们设置了日期2019-05-11,这是当前日期-
> db.getDocumentsExpiredDemo.insertOne({"ArrivalDate":new ISODate("2019-05-11")}); { "acknowledged" : true, "insertedId" : ObjectId("5cd563b17924bb85b3f4893b") } > db.getDocumentsExpiredDemo.insertOne({"ArrivalDate":new ISODate("2019-01-01")}); { "acknowledged" : true, "insertedId" : ObjectId("5cd563bf7924bb85b3f4893c") } > db.getDocumentsExpiredDemo.insertOne({"ArrivalDate":new ISODate("2019-05-10")}); { "acknowledged" : true, "insertedId" : ObjectId("5cd563ca7924bb85b3f4893d") } > db.getDocumentsExpiredDemo.insertOne({"ArrivalDate":new ISODate("2019-02-01")}); { "acknowledged" : true, "insertedId" : ObjectId("5cd563e77924bb85b3f4893e") }
以下是在find()
方法的帮助下显示集合中所有文档的查询-
> db.getDocumentsExpiredDemo.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5cd563b17924bb85b3f4893b"), "ArrivalDate" : ISODate("2019-05-11T00:00:00Z") } { "_id" : ObjectId("5cd563bf7924bb85b3f4893c"), "ArrivalDate" : ISODate("2019-01-01T00:00:00Z") } { "_id" : ObjectId("5cd563ca7924bb85b3f4893d"), "ArrivalDate" : ISODate("2019-05-10T00:00:00Z") } { "_id" : ObjectId("5cd563e77924bb85b3f4893e"), "ArrivalDate" : ISODate("2019-02-01T00:00:00Z") }
以下是查询以获取MongoDB中今天之前过期的文档-
> db.getDocumentsExpiredDemo.find({ "ArrivalDate": { $lte : new Date()}});
这将产生以下输出-
{ "_id" : ObjectId("5cd563bf7924bb85b3f4893c"), "ArrivalDate" : ISODate("2019-01-01T00:00:00Z") } { "_id" : ObjectId("5cd563ca7924bb85b3f4893d"), "ArrivalDate" : ISODate("2019-05-10T00:00:00Z") } { "_id" : ObjectId("5cd563e77924bb85b3f4893e"), "ArrivalDate" : ISODate("2019-02-01T00:00:00Z") }