【问题标题】:Error counting the number of records with a unique value in a field计算字段中具有唯一值的记录数时出错
【发布时间】:2019-03-23 01:51:50
【问题描述】:

我有一个名为 deviceID 的字段,我试图在我的数据库 (MongoDB) 中获取该字段的唯一值的数量。我正在查看this SO post 中的示例,但没有一个对我有用。我正在使用 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)

我可以发布任何有用的附加代码,非常感谢任何帮助。如果我得到这个工作,我会更新这篇文章。提前谢谢你。

克莱顿

编辑 1:

来自我的 Gemfile:

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

解决方案:

正如我需要的代码下面发布的那样

DistributedHealth.distinct('deviceID').count

【问题讨论】:

  • 您使用哪个库/gem 来访问 mongo db?
  • @GavinMiller 请参考 EDIT 1

标签: ruby-on-rails ruby mongodb ruby-on-rails-4 mongoid


【解决方案1】:

你快到了:

DistributedHealth.distinct('deviceID').count

您想使用distinct 获取不同的deviceIDs,然后使用Array#count(或Array#length,如果您想提醒自己您实际上是在计算数组中的元素而不是直接计算元素)查询数据库中的计数)。

【讨论】:

  • 工作就像一个魅力,我非常感谢这一点。谢谢。
猜你喜欢
  • 1970-01-01
  • 2016-08-09
  • 1970-01-01
  • 1970-01-01
  • 2021-09-07
  • 1970-01-01
  • 2012-09-09
  • 1970-01-01
相关资源
最近更新 更多