MongoDB Query to search for records only in a specific hour?


For this, use the $hour operator. Let us first create a collection with documents with one of the field as date −

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

Following is the query to display all documents from a collection with the help of find() method −

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

This will produce the following output −

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

Following is the query to search for specific hours. Here, we will get records for specific hours 8 and 1. The output would display the ID for both the times (hours) −

>db.mongoDbSearchForHoursDemo.aggregate([{$project:{SpecificHours:{$hour:"$OrderDatetime"}}},
{$match:{SpecificHours:{"$in":[08,01]}}}]);

This will produce the following output −

{ "_id" : ObjectId("5cd6e8b86d78f205348bc62b"), "SpecificHours" : 1 }
{ "_id" : ObjectId("5cd6e8f26d78f205348bc62d"), "SpecificHours" : 8 }
raja
Published on 13-Jun-2019 11:50:46
Advertisements