The Crystal Programming Language Forum

MongiDb Date Range Query Issue

When trying to execute the following query

{ $and: [ { "created_at": { $gte: ISODate("2020-05-01T00:00:00.000+0000") } }, { "created_at": { $lt: ISODate("2020-06-01T00:00:00.000+0000") } } ] }

In Ruby, it looks like this (using Mongoid)

data = Data.where(:created_at.gt => Time.parse(yesterday.to_s)).and(:created_at.lt => Time.parse(today.to_s)).all

I’ve tried

collection.find{ $and: [ { "created_at": { $gte: ISODate("2020-05-01T00:00:00.000+0000") } }, { "created_at": { $lt: ISODate("2020-06-01T00:00:00.000+0000") } } ] }.each do |doc|
docs << doc
p doc
end

This generates the following error

Error: $global_variables are not supported, use @@class_variables instead

I’ve tried quoting the globals, e.g…

collection.find{ "$and": [ { "created_at": { "$gte": ISODate("2020-05-01T00:00:00.000+0000") } }, { "created_at": { "$lt": ISODate("2020-06-01T00:00:00.000+0000") } } ] }.each do |doc|
docs << doc
p doc
end

This generates

Error: unexpected token: :

Any suggestions?

Many thanks!

Make sure your quotes are correct, like "$and". Not sure if its just the forums, but ones that are in your example are not exactly correct.

Could you share more of the code/error? If possible maybe make an example that reproduces the issue within https://play.crystal-lang.org/#/cr (minus the actual mongo querying ofc).