Andrew
Andrew

Reputation: 238667

Mongoid: How to return the count of documents matching specific criteria?

I need to return a list of counts (all records, all records matching a certain criteria). I know how to do this using MySQL (SELECT COUNT(*) WHERE ...) but I'm not familiar with how to do this using Mongo and Mongoid. How can I fetch these counts in the most efficient way?

Upvotes: 5

Views: 4441

Answers (2)

francpaul
francpaul

Reputation: 246

Using MongoID you can set the criteria in many ways: http://mongoid.org/docs/querying/criteria.html

Assume Thing is a Ruby class including Mongoid::Document

As an example you can use the where function and you can then get the number of documents matching, by calling the 'count' finder function.:

Thing.where(foo: "bar").count

Upvotes: 1

Pavel Veller
Pavel Veller

Reputation: 6115

From the Mongoid documentation:

Model.count

Returns the number of documents in the database. If you want to specify conditions use where

# Get the count of documents.
Person.count
# Get the count of documents given the provided conditions.
Person.where(title: "Sir").count

From MongoDB documentation:

db.mycollection.count( {active:true} 

Upvotes: 9

Related Questions