Search code examples
mongodbmongoosedatabase-schemaisodate

Date range query for Mongo document field that is an ISOString but not typed Date?


Say I have a collection with documents (from JSON) that include a field with date information - as ISOString (but not Date typed). For example:

{
  foo: {
    completed: "2015-02-25T12:44:47.335Z"
  }
}

How can I perform a date range query on this data? As far as I can tell the field is treated as a String. I'm also using Mongoose. Can I do something in the schema to type this sub-field appropriately?


Solution

  • Converting to a Date type is best, but you can still perform sorting and range filtering on ISO date strings.

    db.test.find({'foo.completed': {
        $gt: '2015-01-25T12:44:47.335Z', 
        $lt: '2015-03-25T12:44:47.335Z'
    }})