Question

I want to filter data by month using mongomapper for sinatra.

At mongo console I'd do it like this

'Filter By January
db.document.find({$where : 'return this.date.getMonth() == 0'})
'Filter By July
db.document.find({$where : 'return this.date.getMonth() == 6'})
'Filter By December
db.document.find({$where : 'return this.date.getMonth() == 11'})

So, what's the equivalent for mongomaper ODM?

Was it helpful?

Solution

I had forgotten this post.

My solution:

# d is my date to filter 
start_time = DateTime.strptime("#{d.year}-#{d.month}-01T00:00:00+00:00", '%Y-%m-%dT%H:%M:%S%z').to_time.utc
end_time   = DateTime.strptime("#{d.year}-#{d.month}-#{d.day}T23:59:59+00:00", '%Y-%m-%dT%H:%M:%S%z').to_time.utc

Document.where(:date => {:$gt => start_time}).where(:date => {:$lte => end_time}).find_each do |doc|
    #Do something with objectexpense.amount
end

Feel free to post a better solution.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top