I have a bunch of posts which have category tags in them. I am trying to find out how many times each category has been used.
I'm using rails with mongodb, BUT I don't think I need to be getting the occurrence of categories from the db, so the mongo part shouldn't matter.
This is what I have so far
@recent_posts = current_user.recent_posts #returns the 10 most recent posts @categories_hash = {'tech' => 0, 'world' => 0, 'entertainment' => 0, 'sports' => 0} @recent_posts do |cat| cat.categories.each do |addCat| @categories_hash.increment(addCat) #obviously this is where I'm having problems end end end
the structure of the post is
{"_id" : ObjectId("idnumber"), "created_at" : "Tue Aug 03...", "categories" :["world", "sports"], "message" : "the text of the post", "poster_id" : ObjectId("idOfUserPoster"), "voters" : []}
I'm open to suggestions on how else to get the count of categories, but I will want to get the count of voters eventually, so it seems to me the best way is to increment the categories_hash, and then add the voters.length, but one thing at a time, i'm just trying to figure out how to increment values in the hash.
If you aren't familiar with map/reduce and you don't care about scaling up, this is not as elegant as map/reduce, but should be sufficient for small sites:
@categories_hash = Hash.new(0)
current_user.recent_posts.each do |post|
post.categories.each do |category|
@categories_hash[category] += 1
end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With