How do I get unique elements in this array?

前端 未结 6 1061
时光取名叫无心
时光取名叫无心 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 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.

提交回复
热议问题