0

I want to find all documents that have "fecha" equal than today's date (considering 'today' is 2017-08-08). "Fecha" property is a string, so I tried this:

db.getCollection('operaciones').find({"fecha_registro": /^2017-08-08/});

It works good on robomongo so Ive been trying to send the "/^2017-08-08/" as a parameter to my api but no success.

Do you know a better way to achieve this? Maybe not send a parameter but use a function in mongo itself?

This are example documents:

{
    "_id" : ObjectId("598910f600e65c6da6a9f643"),
    "fecha" : "2017-08-08T01:16:38.783Z"
}    {
    "_id" : ObjectId("598910f600e65c6da6a9f644"),
    "fecha" : "2017-08-08T01:23:21.183Z"
}    {
    "_id" : ObjectId("598910f600e65c6da6a9f645"),
    "fecha" : "2017-08-09T01:52:31.313Z"
}    {
    "_id" : ObjectId("598910f600e65c6da6a9f646"),
    "fecha" : "2017-08-09T04:36:01.512Z"
}

Thank you

Mario Perez
  • 93
  • 1
  • 11
  • Are you using the MongoDB driver for NodeJS? – Andrew Li Aug 08 '17 at 03:36
  • 1
    It's "much better" to actually convert the "strings" to a BSON Date and then [use a "range" to select between the dates](https://stackoverflow.com/questions/2943222/find-objects-between-two-dates-mongodb) ( a single day is in fact a "range" ). Stored as a BSON Date, this in fact takes **4-bytes** ( length of the long integer value for the timestamp ) as compared to the **24-bytes** to store the "string". Not only does storage take more space, but that also equates to time to load and process, and it's a significant difference, especially over a large amount of data. – Neil Lunn Aug 08 '17 at 03:36
  • @AndrewLi, yes! Using a MEAN stack for this. – Mario Perez Aug 08 '17 at 03:55
  • @NeilLunn.. I can change my dates to BSON format, thanks for the tip! But still, how you I compare to current date? How do i make a range for the current date? – Mario Perez Aug 08 '17 at 03:57
  • Well "today" is usally expressed as `var oneDay = (1000 * 60 * 60 * 24), today = new Date(), today = new Date( today.valueOf() - ( today % oneDay)), tomorrow = new Date(today.valueOf() + oneDay);` and then you simply do `.find({ "fetcha": { "$gte": today, "$lt": tomorrow })`. Various other ways to manipulate dates, but that's the "built in" basics. – Neil Lunn Aug 08 '17 at 04:08

0 Answers0