|
| 1 | +--- |
| 2 | +layout: post |
| 3 | +title: How to query date range in Mongo |
| 4 | +description: "Code snippets showing how to query date ranges in MongoDb. This can work also for a specific |
| 5 | +day. Use only date or datetime." |
| 6 | +author: ama |
| 7 | +permalink: /snippets/60c8a106c807505ef1971306/how-to-query-date-range-in-mongo |
| 8 | +published: true |
| 9 | +snippetId: 60c8a106c807505ef1971306 |
| 10 | +categories: [snippets] |
| 11 | +tags: [mongodb, terminal, shell, codever] |
| 12 | +--- |
| 13 | + |
| 14 | +## Use only the **date** part |
| 15 | +In the following example only the **date** part is set. Time is set to by default to `00:00:00`. So the following query compares all entries _archived_ within *a day* (`2021-06-14`): |
| 16 | + |
| 17 | +```javascript |
| 18 | +var start = new Date("2021-06-14"); |
| 19 | +var end = new Date("2021-06-15"); |
| 20 | + |
| 21 | +db.call_archive.find({archivedAt: {$gte: start, $lt: end}}).pretty(); |
| 22 | + |
| 23 | +``` |
| 24 | + |
| 25 | +## Use both **date** and **time** |
| 26 | + |
| 27 | +You can also specify the Time in ISO format |
| 28 | +- `new Date("<YYYY-mm-ddTHH:MM:ss>")` - specifies the datetime in the client's local timezone and returns the ISODate with the specified datetime in UTC |
| 29 | +- `new Date("<YYYY-mm-ddTHH:MM:ssZ>") ` - specifies the datetime in UTC and returns the ISODate with the specified datetime in UTC |
| 30 | + |
| 31 | +```javascript |
| 32 | +var start = new Date("2021-06-14T13:13:13Z"); |
| 33 | +var end = new Date("2021-06-14T14:13:13Z"); |
| 34 | + |
| 35 | +db.call_archive.find({archivedAt: {$gte: start, $lt: end}}).sort({archivedAt: -1}).pretty(); //sort descending |
| 36 | +``` |
| 37 | + |
| 38 | +<span style="font-size: 0.9rem"> |
| 39 | + <strong>Reference - </strong> |
| 40 | + <a href="https://docs.mongodb.com/manual/reference/method/Date/" target="_blank" style="font-weight: lighter"> |
| 41 | + https://docs.mongodb.com/manual/reference/method/Date/ |
| 42 | + </a> |
| 43 | +</span> |
| 44 | + |
| 45 | +<hr/> |
| 46 | + |
| 47 | + {% include snippet-post-recommendation-ending.html snippetId="60c8a106c807505ef1971306" %} |
0 commit comments