Querying distinct with MongoMapper

≡放荡痞女 提交于 2019-12-07 19:10:50

问题


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?


回答1:


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




回答2:


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




回答3:


Try this

subscribedToThread = Comment.where(:subscribe_thread => 1).fields(:user_id).collect(&:user_id).uniq 

It will show you list of uniq user_id



来源:https://stackoverflow.com/questions/9098605/querying-distinct-with-mongomapper

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!