I’m working on a simple project where I have two sample referenced models:
class Player
include Mongoid::Document
include Mongoid::Timestamps
has_and_belongs_to_many :games
end
class Game
include Mongoid::Document
include Mongoid::Timestamps
has_and_belongs_to_many :players
end
What I need to do is get a list of top games played with count of players. Similar to this:
{
"diablo_3": {
"players": 89
},
"max_payne_3": {
"players": 87
},
"world_of_warcraft": {
"players": 65
},
"dirt_3": {
"players": 43
}
}
Thanks
You can use the MongoDB group command to do some server-size processing on a single collection,
and it is available as a method on the collection in the Ruby driver,
see http://api.mongodb.org/ruby/current/Mongo/Collection.html#group-instance_method
Below please find a test based on your models, with the title field added to your Game model.
This is a working answer to your question that uses MongoDB’s group command.
result