4

我需要返回一个计数列表(所有记录,所有符合特定条件的记录)。我知道如何使用 MySQL ( SELECT COUNT(*) WHERE ...) 来做到这一点,但我不熟悉如何使用 Mongo 和 Mongoid 来做到这一点。如何以最有效的方式获取这些计数?

4

2 回答 2

7

Mongoid 文档

模型计数

返回数据库中的文档数。如果要指定条件,请使用where

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

来自MongoDB 文档

db.mycollection.count( {active:true} 
于 2012-05-14T20:10:11.693 回答
1

使用 MongoID,您可以通过多种方式设置条件:http: //mongoid.org/docs/querying/criteria.html

假设 Thing 是一个 Ruby 类,包括 Mongoid::Document

例如,您可以使用 where 函数,然后可以通过调用 'count' finder 函数获取匹配的文档数量。:

Thing.where(foo: "bar").count
于 2012-05-14T20:18:25.713 回答