0

In Mongoose/MongoDB Schema if I use type of created_at field as String instead of Date, will it increase the time taken by my query when I fetch my results sorted according to created_at field or not? Also will there be any other significant performance issues if I use String but not Date?

A. Mashreghi
  • 1,729
  • 2
  • 20
  • 33
Sudhanshu Gaur
  • 7,486
  • 9
  • 47
  • 94
  • why would you want to? – Alex Nov 09 '17 at 19:19
  • why would you want to? – Alex Nov 09 '17 at 19:19
  • I have some documents already storing `created_at` field as `String` that's why i thought if there won't be any problem then will keep it as it is. – Sudhanshu Gaur Nov 09 '17 at 19:20
  • you won't be able to query on date / time if it's stored as a string – Alex Nov 09 '17 at 19:24
  • which type of query you are talking about. Also i am calling my documents based on sorted order of this `created_at` field but it is working fine AFAIK(but not sure that's why i asked this question). – Sudhanshu Gaur Nov 09 '17 at 19:26
  • what do the dates (in string format) look like in your documents? – Alex Nov 09 '17 at 19:30
  • `"2017-05-16T02:08:48.419+05:30"` – Sudhanshu Gaur Nov 09 '17 at 19:32
  • The reason you're seeing sorting working is because `2017-05-16T02:08:48.419+05:30` is > `2016-05-16T02:08:48.419+05:30` (sorted a-z as a string) I would always store dates, as dates, however. – Alex Nov 09 '17 at 19:36
  • Yes I know that's why in the first place I didn't think there will be any problem, sorting was working fine. But now this point came to my mind and I want to know will there be any problem or not ?? – Sudhanshu Gaur Nov 09 '17 at 19:41
  • if all you're doing is sorting like that, there won't be a problem. You won't however, be able to query for documents with a date 'in range' - for example between two dates – Alex Nov 09 '17 at 19:46
  • @Alex By using $gt and $lt I can still use my `created_at` field to find documents between two dates. – Sudhanshu Gaur Nov 09 '17 at 19:48
  • Possible duplicate of [Query the string type Date in mongodb](https://stackoverflow.com/questions/9314271/query-the-string-type-date-in-mongodb) – Alex Nov 09 '17 at 19:51
  • @Alex thanks, Acc to your post if the user wanted to fetch results modified a day before then he can get them by using $gt and and for comparing time he can use Date.now() and from that Date.now() he can use previous date. like if current date is `"2017-05-16T02:08:48.419+05:30"` then he will write the query `db.collection.find({"createdAt" : { $gte : new ISODate("2017-05-15T02:08:48.419+05:30") }});` – Sudhanshu Gaur Nov 09 '17 at 21:25
  • @Alex are you there ?? – Sudhanshu Gaur Nov 10 '17 at 20:13
  • yes, that's right – Alex Nov 10 '17 at 22:41

0 Answers0