Fetch data for a period of days

I have data in MongoDB with date format 14-May-2023 and May 14, 2023. What I want is to fetch data depending on range provide such as I need data from 01-May-2023 to 31-May-2023 and so on. Can anyone help me on how can I achieve this. I have input type-“date” in frontend side in React.js. Thanks

Hey @Prabjot_Singh,

Could you please confirm whether these values are stored as String or Date data types in the MongoDB documents?

However, I think that you’ll likely need to convert these date strings into the MongoDB Date format and then use the $gte and $lte operators to filter the documents within the desired date range. Moving forward, I would recommend ensuring consistency in the date format within your MongoDB documents. This will help maintain data integrity and streamline your queries.

If you need the date in a different format for the React.js part of your application, consider using a library like moment.js or the built-in JavaScript Date object for easy conversion.

I hope it helps!

Best regards,

Note that you have 2 ways

Dynamically convert when you query

This will be slow every time since your query will not be able to use any index.

Permanently convert using an aggregation to overwrite the current date fields

This will be slow once during the migration to the appropriate format. After the query will be fast as an index could be used.

1 Like