计算字段中具有唯一值的记录数时出错

Error counting the number of records with a unique value in a field

我有一个名为 deviceID 的字段,我正在尝试获取数据库中该字段的唯一值的数量 (MongoDB)。我正在查看 this SO post 中的示例,但其中 none 对我有用。我正在使用 Rails 4.2.2,并且我还有这些代码行目前正在运行:

示例 1:

<p id="total">Total number of database entries: <%= DistributedHealth.count %></p>

示例 2:

<% @distributed_healths.each do |distributed_health| %>
  <tr>
    <td><%= distributed_health.deviceID %></td>
  </tr>
<% end %>

这些是我完成这项工作的一些失败尝试。

失败的尝试 #1:

<%= DistributedHealth.distinct.count(:deviceID) %>

#1 错误:

wrong number of arguments (0 for 1)

失败的尝试 #2:

<%= DistributedHealth.distinct.count('deviceID') %>

#2 错误:

wrong number of arguments (0 for 1)

失败的尝试 #3(我知道这是 Rails 3 但我很绝望):

<%= DistributedHealth.count('deviceID', :distinct => true) %>

#3 错误:

wrong number of arguments (2 for 0)

我可以 post 任何有用的额外代码,非常感谢任何帮助。如果我能正常工作,我会更新这个 post。提前谢谢你。

克莱顿

编辑 1:

来自我的 Gemfile:

gem 'mongoid'
gem "moped"
gem 'bson_ext'

解决方案:

在下面 posted 我需要的代码是

DistributedHealth.distinct('deviceID').count

你快完成了:

DistributedHealth.distinct('deviceID').count

如果您想提醒自己,您实际上是在计算数组中的元素而不是直接查询数据库以获取计数,则需要使用 distinct and then count them using Array#count (or Array#length 获取不同的 deviceIDs) .