ruby-on-rails-3mongodbmongomapper

Querying distinct with MongoMapper


How do I query distinct with MongoMapper? My query is:

subscribedToThread = Comment.where(:subscribe_thread => 1).all

But this will return many objects with the same user_id. I need to return just a distinct user_id. Is this possible?


Solution

  • I think you will need to drop down to the ruby driver in order to do this as I don't think you can do this with MongoMapper itself:

    subscribedToThread = Comment.collection.distinct("user_id", {:subscribe_thread => 1})
    

    Calling the collection method on a model returns the collection as would be provided by the Ruby driver directly so you can issue a distinct query using the syntax below:

    collection.distinct(key, query = nil)

    You can read more about it here