Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to search date in mongodb string format

Please advise how to search in date format in MongoDB

my mongodb data data type is string

{ymdhis:"2023-03-14T09:10:37.000+00:00"}

The date of that form is stored in the form of a string. How do I retrieve it?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

For example, I want to search like this

{ymdhis:{'$gte':2023-03-14 00:00:00,'$lte':2023-03-14 23:59:59}}

to my javascript code this no results

{'todate':{'$toDate':'$ymdhis'}}
{'ymdhis':{'$gte':new Date(new Date('2023-03-14 00:00:00').getTime()+9*3600000)}}

how can i get the result

>Solution :

To search for a date in MongoDB, you can use the $gte (greater than or equal to) and $lte (less than or equal to) operators with a Date object. Here’s an example of how to search for all documents where the ymdhis field is between 2023-03-14 00:00:00 and 2023-03-14 23:59:59:

db.collection.find({
  ymdhis: {
    $gte: new Date('2023-03-14T00:00:00.000Z'),
    $lte: new Date('2023-03-14T23:59:59.999Z')
  }
})

Note that you need to pass the date string in ISO 8601 format and create a Date object in the query. In the example above, I’ve used the Z timezone specifier to indicate that the date is in UTC time. You can adjust the timezone by changing the date string accordingly.

If your ymdhis field is stored as a string, you can convert it to a Date object in the query using the $toDate aggregation operator, like this:

db.collection.aggregate([
      {
        $addFields: {
          ymdhisDate: {
            $toDate: '$ymdhis'
          }
        }
      },
      {
        $match: {
          ymdhisDate: {
            $gte: new Date('2023-03-14T00:00:00.000Z'),
            $lte: new Date('2023-03-14T23:59:59.999Z')
          }
        }
      }
    ])

In this example, the $addFields stage creates a new ymdhisDate field that contains a Date object converted from the ymdhis string field. The $match stage then uses the ymdhisDate field to filter the documents based on the date range.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading