Reputation: 43589
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?
Upvotes: 2
Views: 1563
Reputation: 3235
For the original post, try this:
subscribedToThread = Comment.where(:subscribe_thread => 1).distinct(:user_id)
I wanted to count the number of distinct entries when the user chose type = "Other" from the list and entered a custom name (so that I could consider adding more common choices to the list).
InteriorInfo.where(type: 'Other').distinct(:name).sort.each{|i| puts "%3d %s" % [InteriorInfo.where(name: i).count, i]}
Resulting in (snippet)
6 AED
1 Alarm Panel
16 Basement Access
Upvotes: 0
Reputation: 30156
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
Upvotes: 7
Reputation: 921
Try this
subscribedToThread = Comment.where(:subscribe_thread => 1).fields(:user_id).collect(&:user_id).uniq
It will show you list of uniq user_id
Upvotes: 1
Reputation: 8478
Yes, you can do so:
subscribedToThread = Comment.where(:subscribe_thread => 1).fields(:user_id).all.compact!.unique!
This will nil every field but user_id which you then uniq!
,ie you remove all doubles and then compact!
all nil
http://mongomapper.com/documentation/plugins/querying.html#fields
Upvotes: 2