dneumark
dneumark

Reputation: 286

Conditions about the fields in mongoid

I have a User Class which has_many sessions. I would like to write a query that count the number of sessions each user have, in a specific time range.

In other words, I'm looks for a query that looks something like that: User.where(:sessions.date => date1..date2)

What is the right way to approach this?

Upvotes: 1

Views: 43

Answers (1)

Thomas R. Koll
Thomas R. Koll

Reputation: 3139

Personally I use simple $gt and $lt for this as it allows to query just for one of them, but of course there is also a $in operator.

# Session seems to be a separate collection
sessions = Session.where(:date => {"$gt" => date1, "$lt" => date2})
User.find(sessions.collect(&:user_id).uniq)

Aside this, your query looks a perfect candidate for an aggregation pipeline to transfer less data from the db in the Session query.

Upvotes: 1

Related Questions