2

Suppose I have a user document who has many activities as an embedded document. Every time a user does something on the site an activity document is created (as an example).

class User
  include Mongoid::Document
  has_many :activities
end

class Activity
  include Mongoid::Document
  field :action_executed_at, type: DateTime
  belongs_to :user
end

I now want to query all the users with an activity after today. Can this be done with Mongoid? I tried queries like:

User.where("activities.action_executed_at" => {"$gt" => DateTime.now.to_s})

And even:

User.where("activities" => {
  "$elemMatch" => { 
     "action_executed_at" => {
       "$gt" => DateTime.now.to_s 
      } 
   } 
})

But they always return and empty collection.

Ross
  • 1,313
  • 4
  • 16
  • 24
Cimm
  • 4,653
  • 8
  • 40
  • 66

1 Answers1

2

try this

User.where(:'activities.action_executed_at'.gt => DateTime.now)
abhas
  • 5,193
  • 1
  • 32
  • 56
  • No success. As soon as I call count on these `where` methods Mongoid tells me: "BSON::InvalidDocument: Cannot serialize an object of class DateTime into BSON." Could this be a smell that something else is going wrong? – Cimm Sep 25 '12 at 06:32
  • Thanks, tried that already but it always returns 0 results. I was thinking it might be a sign there is something else I am doing wrong? – Cimm Sep 25 '12 at 07:23
  • No, I am sorry, no solution yet. I have a workaround but it's not solved. Will report back if I find it. – Cimm Oct 01 '12 at 12:04