chiku
chiku

Reputation: 433

date range query in mongodb 3.6

I want to query mongodb for retrieving records from the today midnight to current time, but its giving an error in the query , please help Sample Records :

 {
 "myDate" : ISODate("2017-07-17T11:06:17.874Z"),
"_id":"xxxx"
  }
  ,
  {
 "myDate" : ISODate("2017-07-17T11:06:17.874Z"),
"_id":"yyy"
  }


 db.runReadCommand(
 {
aggregate : 'mycollection',
pipeline : [

{$project : {a:new Date (),myDate:1}},
{$project : {myDate:1,a:1,
    b : {$dateFromString : { dateString : {$dateToString:{date : '$a',format: "%Y-%m-%d"}}}}}}
 ,{$match : {myDate: {$lte : a}}}
],cursor:{batchSize : 10}})

Regards Kris

Upvotes: 1

Views: 412

Answers (2)

Buzz Moschetti
Buzz Moschetti

Reputation: 7621

An approach without requiring moment:

var r = [
     // These are not today:
 {_id:0, ts: new ISODate("2018-07-26T07:00:00.000Z")}
,{_id:1, ts: new ISODate("2018-07-26T22:00:00.000Z")}

     // These are today and before now (when I wrote this)
,{_id:2, ts: new ISODate("2018-07-27T00:00:00.000Z")}
,{_id:3, ts: new ISODate("2018-07-27T10:00:00.000Z")}

     // These are AFTER now (when I wrote this)
,{_id:4, ts: new ISODate("2018-07-27T20:00:00.000Z")}
,{_id:5, ts: new ISODate("2020-01-01T20:00:00.000Z")} // the future!
 ];

db.foo.drop();
db.foo.insert(r);

now = new Date(); 
sod = new Date(now);

// Cheapo way to set time elements to midnight:
sod.setHours(0);
sod.setMinutes(0);
sod.setSeconds(0);
sod.setMilliseconds(0);

print("now: " + now);
print("sod: " + sod);

db.foo.aggregate([
{$match: {$and: [ {ts: {"$gte": sod}}, {ts: {"$lt": now}} ]  }}
            ]);

Upvotes: 1

Ashh
Ashh

Reputation: 46491

You can use moment library to find start of the day and the present time

With just a find query

db.collection.find({
  myDate: {
    $gte: moment().startOf("day").toDate(),
    $lte: moment().toDate()
  }
})

With aggregation

db.runReadCommand(
  {
    aggregate: "mycollection",
    pipeline: [
      { $match: {
        myDate: {
          $gte: moment().startOf("day").toDate(),
          $lte: moment().toDate()
        }
      }}
    ]
  }
)

Upvotes: 1

Related Questions