0

I have two fields in database start_date and end_date. How to find if date which i am passing is in between these two dates.

Model

class Schedule
  include Mongoid::Document

  field :start_date, type: Date
  field :end_date, type: Date

end

Simple activerecord query would be

Schedule.where(["start_date <= ? AND end_date >= ?", params[:date], params[:date] ])

Date is saved in database in following format

{
"_id" : ObjectId("559d182f6368611dbf000000"),
"start_date" : ISODate("2015-06-10T00:00:00.000Z"),
"end_date" : ISODate("2015-07-10T00:00:00.000Z")

}

and my parameter contain date like "2015-06-10"

What will be the query while using MongoDB database with Mongoid?

Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
chaitanya
  • 1,974
  • 3
  • 17
  • 35
  • possible duplicate of [Find objects between two dates MongoDB](http://stackoverflow.com/questions/2943222/find-objects-between-two-dates-mongodb) – Blakes Seven Jul 08 '15 at 12:50
  • 1
    @BlakesSeven: this is higher level access, though. – Sergio Tulentsev Jul 08 '15 at 12:51
  • @SergioTulentsev Said "Mongoid" which can use the same principles. Still don't see the justification for another duplicate question though. Search engines work. – Blakes Seven Jul 08 '15 at 12:52
  • @BlakesSeven: can use, yes, but mongoid-native method is better. – Sergio Tulentsev Jul 08 '15 at 12:53
  • @SergioTulentsev Translation of a string taking CPU cycles is better? We have different learning principles. Anyhow I'm talking to the OP now saying "your date argument is a string" you need to supply an Object that casts to a `Date` than can be serialized to a BSON query. – Blakes Seven Jul 08 '15 at 12:55
  • @BlakesSeven: date parsing must happen anyway and CPU cycles will be burned. These things being equal, it's better to have nicer code :) – Sergio Tulentsev Jul 08 '15 at 12:58
  • @SergioTulentsev "nicer" to read does not equal "nicer" performance. You seem to fighting a loosing war here to justify your answer and presuming that a lower rep score means less knowlege. I don't see how this is productive. Your answer is either accepted or not. Either way my opinion is the question does not need to be here as it is clearly documented elsewere. – Blakes Seven Jul 08 '15 at 13:01
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/82711/discussion-between-sergio-tulentsev-and-blakes-seven). – Sergio Tulentsev Jul 08 '15 at 14:30

1 Answers1

3

This should work

 Schedule.where(:start_date.lte => date, :end_date.gte => date)
Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
  • Thanks for the right answer, next time i will surely do more search about question, before posting it.. – chaitanya Jul 09 '15 at 05:51