为此,请使用$hour运算符。让我们首先创建一个文档集合,其中一个字段作为日期-
> db.mongoDbSearchForHoursDemo.insertOne({"CustomerName":"Larry","OrderDatetime":new ISODate("2019-01-31 09:45:50")}); { "acknowledged" : true, "insertedId" : ObjectId("5cd6e8a86d78f205348bc62a") } > db.mongoDbSearchForHoursDemo.insertOne({"CustomerName":"Larry","OrderDatetime":new ISODate("2019-02-21 01:10:01")}); { "acknowledged" : true, "insertedId" : ObjectId("5cd6e8b86d78f205348bc62b") } > db.mongoDbSearchForHoursDemo.insertOne({"CustomerName":"Larry","OrderDatetime":new ISODate("2019-04-01 04:10:11")}); { "acknowledged" : true, "insertedId" : ObjectId("5cd6e8e26d78f205348bc62c") } > db.mongoDbSearchForHoursDemo.insertOne({"CustomerName":"Larry","OrderDatetime":new ISODate("2019-05-11 08:53:01")}); { "acknowledged" : true, "insertedId" : ObjectId("5cd6e8f26d78f205348bc62d") }
以下是在find()
方法的帮助下显示集合中所有文档的查询-
> db.mongoDbSearchForHoursDemo.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5cd6e8a86d78f205348bc62a"), "CustomerName" : "Larry", "OrderDatetime" : ISODate("2019-01-31T09:45:50Z") } { "_id" : ObjectId("5cd6e8b86d78f205348bc62b"), "CustomerName" : "Larry", "OrderDatetime" : ISODate("2019-02-21T01:10:01Z") } { "_id" : ObjectId("5cd6e8e26d78f205348bc62c"), "CustomerName" : "Larry", "OrderDatetime" : ISODate("2019-04-01T04:10:11Z") } { "_id" : ObjectId("5cd6e8f26d78f205348bc62d"), "CustomerName" : "Larry", "OrderDatetime" : ISODate("2019-05-11T08:53:01Z") }
以下是查询特定时间的查询。在这里,我们将获得特定时间8和1的记录。输出将显示两个时间(小时)的ID-
>db.mongoDbSearchForHoursDemo.aggregate([{$project:{SpecificHours:{$hour:"$OrderDatetime"}}}, {$match:{SpecificHours:{"$in":[08,01]}}}]);
这将产生以下输出-
{ "_id" : ObjectId("5cd6e8b86d78f205348bc62b"), "SpecificHours" : 1 } { "_id" : ObjectId("5cd6e8f26d78f205348bc62d"), "SpecificHours" : 8 }