简体   繁体   中英

mongoid group_by return a hashmap instead of array of hashes

I want to retrieve a hashmap from a mongoid group_by instead of a array

Product.group_by {|p| p.user_id }

returns an array of mappings

result = Product.group_by {|p| p.user_id } 

=> [ {"12354asdf" => [product1, product2, product3]},
{"safakjgh314" => [product4, product5, product6]} ]

I'm currently running the result of this query over the following to achieve a single hash of mappings

result.reduce Hash.new, :merge

=> {"12354asdf" => [product1, product2, product3], "safakjgh314" => [product4, product5, product6]}

is there a more efficient way to do this?

edit*** After grouping I'd rather operate over the collection with an enumerable that makes sense.

result.each do |k v| k v end

rather than

result.each do |h| h.keys.first, h.values.first end

example of what it currently returns.

[ 
  {user_object => [item1, item2, item3] },
  {user2_object => [item1, item2, item3] },
  {user2_object => [item1, item2, item3] }
]

Regarding the more compact way to iterate over the array of hashes, you can take each element's first :

result.map(&:first).each do |k, v|
  puts k
  puts v.count
end
# 12354asdf
# 3
# safakjgh314
# 3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM