Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 592
Andrew Avatar asked Feb 21 '23 12:02

Andrew


1 Answers

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} 
like image 82
Pavel Veller Avatar answered Apr 29 '23 19:04

Pavel Veller