Question

I'm trying to find all documents by the current day and month like this:

Kid.where("birthday.day" => Time.now.day, "birthday.month" => Time.now.month).first

and I always get nil, event if I try to find all documents like this

Kid.where("birthday.day" => Time.now.day, "birthday.month" => Time.now.month).all.to_a

I did not get anything. But I have records with this day and month.

So I'm definitely doing something wrong.

Any help please

Was it helpful?

Solution

Never a truly great idea unless you can actually present a $match range on the dates you intend to look at, but the aggregate() method allows you to dissect dates in this fashion:

Kid.collection.aggregate([
    { "$project" => {
        "birthday" => {
            "day" => { "$dayOfMonth" => "$birthday" },
            "month" => { "$month" => "$birthday" },
        },
        // other fields you want in the result
    }},
    { "$match" => {
        "birthday.day" => Time.now.day,
        "birthday.month" => Time.now.month
    }}
])

And that is generally in the "moped" syntax since that is what is currently supported under mongoid.

The point being that the MongoDB query translations are not "ruby code" and therefore need a "more strict" translation to what is actually allowed under the syntax. So you cannot access a day or month property of a "date type" field in your data-store in the way that you have tried. Instead you use the internal functions.

Not really different to SQL at all, just do not expect the object translation magic to do anything more "magical" than what can be reasonably expected.

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