How to convert a datefield from string to date?

Posted on

Question :

Here is the query that I am using. What I need to extract is the data for the last 10 minutes. But no records found is the output for this query, I think this is due to the type of data that were inserted to created_at field, it should be date field but string were inserted. How to convert this field so I can use it on the $match

db.collectionName.aggregate([{
   $match : {
        created_at : {
               $gte : new Date(ISODate().getTime() - 1000 * 60 * 10)
                     }
            }
      }]);

Answer :

You’ll need to run a script to detect for integer/string based values and replace them with the standard Mongo/ISO Date standard.

https://docs.mongodb.com/manual/reference/method/Date/

Leave a Reply

Your email address will not be published. Required fields are marked *