简体   繁体   中英

Use MongoID to find a record by month and day, ignoring year and time

I have a model (Events) with five years worth of records (one record per day). I need a method that, when passed a date object such as 2011-12-25 00:00:00, will show me ALL the records that have happened on 12/25 (querying against the :created_at column), regardless of the year or time that's passed.

I tried the following query to retrieve data that are in between given date but i got an issue after year change my query not able to retrieve records. for example record sdate="1-06-2013" and edate ="2-2-2014" i want records of 1st January then how can i get this data.

db.events.find( "this.sdate.getMonth() > 6 && this.edate.getMonth() < 6" );

I need exact following query using in Mongoid rather than ActiveRecord

Model.where("MONTH(created_at) = ? and DAY(created_at) = ?", somedate.month, somedate.day)

Edit: (My first answer missed the fact that it should ignore year and time)

Use the aggregation pipeline as such:

project = { '$project' => { 
              'day' => { '$dayOfMonth' => '$created_at' },
              'month' => { '$month' => '$created_at' }
            }
          }
match = { '$match' => { 'day' => 25, 'month' => 12 } }

Events.collection.aggregate([project, match])

This should return you an array of hashes with the projected values of day and month as well as the matching events' _ids. You could then map them back to Events or whatever you need to do with them.

You could try to do some Javascripting query

db.mydatabase.mycollection.find({$where : 'return this.date.getMonth() == 11'})

But I would never do this. What I would do is store the month-day in a field, have a index on it, and have a faster query. Otherwise you will be scanning all dos.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM