Sarkis Arutiunian Sarkis Arutiunian - 3 months ago 37
Node.js Question

MongoDb query by Date if date stored like String

have a small trouble. Recently merge existed Db from SQL to MongoDb, and all date fields like (createdAt, updatedAt) in SQL and now in MongoDb was stored as String:

"Mon Aug 23 2016 09:55:04 GMT-0700 (PDT)"
so question is. Can I use MongoDb query methods like
$gte, $lt
to fetch particular data? or do I have any other approach to do that, without reconverting whole db, and change data fields to MongoDb date object?

Answer

You need to use below syntax to query datetime fields stores as string

db.mycollection.find({
    "timestamp" : {"$gte": new Date("2013-10-01T00:00:00.000Z")}
})

or

db.mycollection.find({
    "timestamp" : {"$gte": ISODate("2013-10-01T00:00:00.000Z")}
})

The mongo shell provides various methods to return the date, either as a string or as a Date object:

  • Date() method which returns the current date as a string.
  • new Date() constructor which returns a Date object using the ISODate() wrapper.
  • ISODate() constructor which returns a Date object using the ISODate() wrapper.
Comments