Mongoid Criteria: How to count number of documents that have a field with specific value

StackOverflow https://stackoverflow.com/questions/23528976

  •  17-07-2023
  •  | 
  •  

Pergunta

Criteria is as follows:

#<Mongoid::Criteria
  selector: {"_id"=>{"$in"=>["535988c59bb8f9128c000001", 
                             "53598a439bb8f9f211000001",    
                             "536a9300ae4da1b0a9000002"]}}
  options:  {:limit=>5}
  class:    User
  embedded: false>

I want to traverse these users and get a count of how many have attribute is_active: true. I'm thinking there has to be another way rather than doing users.each do |user| and keep a running count of whether the user met that criteria. Any suggestions?

Foi útil?

Solução

If you have that criteria in a variable:

query = User.where(:id.in => ids).limit(5)

then you can add another condition by calling where:

query = query.where(:is_active => true)

and then count them:

n = query.count
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top