How do I get unique elements in this array?

前端 未结 6 1046
时光取名叫无心
时光取名叫无心 2021-01-30 06:11

Using Mongoid. Unfortunately, Mongoid does not allow for selecting unique / distinct! Have gotten these results. As you can see, there are 7 results. If you look carefully (at

相关标签:
6条回答
  • 2021-01-30 06:47

    Errr, it's a bit messy in the view. But I think I've gotten it to work with group (http://mongoid.org/docs/querying/)

    Controller

    @event_attendees = Activity.only(:user_id).where(:action => 'Attend').order_by(:created_at.desc).group
    

    View

    <% @event_attendees.each do |event_attendee| %>    
      <%= event_attendee['group'].first.user.first_name %>
    <% end %>
    
    0 讨论(0)
  • 2021-01-30 06:51

    You can just use the method uniq. Assuming your array is ary, call:

    ary.uniq{|x| x.user_id}
    

    and this will return a set with unique user_ids.

    0 讨论(0)
  • 2021-01-30 06:58

    For those hitting this up in the future, you can now use the Mongoid::Criteria#distinct method from Origin to select only distinct values from the database:

    # Requires a Mongoid::Criteria
    Attendees.all.distinct(:user_id)
    

    http://mongoid.org/en/mongoid/docs/querying.html (v3.1.0)

    0 讨论(0)
  • 2021-01-30 06:58

    Have you looked at this page?

    http://www.mongodb.org/display/DOCS/Aggregation#Aggregation-Distinct

    That might save you some time?

    eg db.addresses.distinct("zip-code");

    0 讨论(0)
  • 2021-01-30 07:06

    Instead of using an Array, consider using either a Hash or a Set.

    Sets behave similar to an Array, only they contain unique values only, and, under the covers, are built on Hashes. Sets don't retain the order that items are put into them unlike Arrays. Hashes don't retain the order either but can be accessed via a key so you don't have to traverse the hash to find a particular item.

    I favor using Hashes. In your application the user_id could be the key and the value would be the entire object. That will automatically remove any duplicates from the hash.

    Or, only extract unique values from the database, like John Ballinger suggested.

    0 讨论(0)
  • 2021-01-30 07:10

    This should work for you:

    Consider Table1 has a column by the name of activity which may have the same value in more than one record. This is how you will extract ONLY the unique entries of activity field within Table1.

    #An array of multiple data entries
    @table1 = Table1.find(:all) 
    
    #extracts **activity** for each entry in the array @table1, and returns only the ones which are unique 
    
    @unique_activities = @table1.map{|t| t.activity}.uniq 
    
    0 讨论(0)
提交回复
热议问题