Shashidhar Gr
Shashidhar Gr

Reputation: 418

mongodb query to get documents within two date range

my documents have a field with date type as below.

{ 
    "_id" : ObjectId("568bae0fcfe23a50879d45fc"),
    "data": {
          "createdDate" : ISODate("2015-12-17T22:25:24.973+0000")
    }
}

how can i get all documents where data.createdDate <= todayDate and data.createdDate >= todayDate-20days.

i tried with below query, which is working fine.

db.myTable.aggregate([
    {$match: {"data.createdDate": {$lte: new Date(), $gte: new Date(new Date().setDate(new Date().getDate()-20))}}}
])

but this query considers time also. I want to compare only with respect to date.

Upvotes: 1

Views: 753

Answers (1)

Ganesh Karamala
Ganesh Karamala

Reputation: 513

if you want to compare with respect to date , you should set createdDate with hours, minutes, seconds and milliseconds to zero before storing into database.

If you have such date in db, try below query

 db.collection.aggregate([
    {$match: {"data.createdDate": {$lte: new Date().setHours(0,0,0,0), $gte: new Date(new Date().setDate(new Date().getDate()-20)).setHours(0,0,0,0)}}}
])

Upvotes: 2

Related Questions