0

I need to select documents with "entryDateTime" between two given dates => minDate, maxDate. This is my "find" method:

var cursor = db.collection('Invoices').find({'workplace': String(client._id)});

I found that mongodb stores the date as a STRING:

2017-05-26T21:00:00.000Z

Yet the minDate and maxDate are of Date type. When I try to convert them to String, it won't work (always returns "true").

How can I select only the documents with "entryDateTime" between those two dates?

I'm working with Nodejs.

I have found another question where the date is stored like that: "Sun May 30 18:47:06 +0000 2010". I'm not sure about the difference between the two ways these dates are stored.

Gil
  • 55
  • 7
  • No. MongoDB does not store as a string. Bad code stores it as a string. Are you sure they are strings? What does the data look like from the mongo shell? Note that `console.log()` just "stingifies", so it's not really an indication. The shell will tell us for certain. – Neil Lunn Jun 29 '17 at 12:22
  • Does not really matter if they are strings, since even so it's in ISO format, so the answer remains the same. String or no string. – Neil Lunn Jun 29 '17 at 12:23
  • This is the code storing it in the database: invoice.entryDateTime = new Date(); Then I insert invoice into the database – Gil Jun 29 '17 at 12:26
  • According to the mongo shell, it is stored as a string - "entryDateTime": "2017-05-26T21:00:00.000Z" – Gil Jun 29 '17 at 12:28
  • Like i said *"This does not matter"* The strings are in ISO format, therefore a "range query" [just like the answers on the duplicate question show you](https://stackoverflow.com/questions/2943222/find-objects-between-two-dates-mongodb) is what you need to search "between". But fix your dates. Strings take up more space than a `Date` does. – Neil Lunn Jun 29 '17 at 12:29
  • As for the code storing as string. My bet is you are using an ODM like mongoose and have defined the schema type as `String` rather than `Date` and that is what happens. Fix your code. – Neil Lunn Jun 29 '17 at 12:31
  • I haven't defined a schema. I'm not sure what mongoose is. I store the data in a MongoDB database. On a different note, how do you give the grey background for the "String" and "Date" words? – Gil Jun 29 '17 at 12:36
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/147932/discussion-between-gil-and-neil-lunn). – Gil Jun 29 '17 at 12:36

0 Answers0