Reputation: 299
I have a field called deviceID
and I am trying to get the number of unique values of that field in my database (MongoDB). I was looking at examples in this SO post, yet none of them were working for me. I am using Rails 4.2.2 and I also have these lines of code currently working:
Example 1:
<p id="total">Total number of database entries: <%= DistributedHealth.count %></p>
Example 2:
<% @distributed_healths.each do |distributed_health| %>
<tr>
<td><%= distributed_health.deviceID %></td>
</tr>
<% end %>
These are some of my failed attempts at getting this done.
Failed attempt #1:
<%= DistributedHealth.distinct.count(:deviceID) %>
Error for #1:
wrong number of arguments (0 for 1)
Failed attempt #2:
<%= DistributedHealth.distinct.count('deviceID') %>
Error for #2:
wrong number of arguments (0 for 1)
Failed attempt #3 (I know this is for Rails 3 but I was desperate):
<%= DistributedHealth.count('deviceID', :distinct => true) %>
Error for #3:
wrong number of arguments (2 for 0)
I can post any additional code that would be helpful, any help is greatly appreciated. I will update this post if I get this working. Thank you in advance.
Clayton
EDIT 1:
From my Gemfile:
gem 'mongoid'
gem "moped"
gem 'bson_ext'
SOLUTION:
As was posted below the code I needed was
DistributedHealth.distinct('deviceID').count
Upvotes: 0
Views: 336
Reputation: 434805
You're almost there:
DistributedHealth.distinct('deviceID').count
You want to grab the distinct deviceID
s using distinct
and then count them using Array#count
(or Array#length
if you want to remind yourself that you're really counting the elements in an array rather than directly querying the database for the count).
Upvotes: 1