Mongoid - limit on distinct query

老子叫甜甜 提交于 2019-12-10 19:07:04

问题


I am trying to put a limit on the number of distinct results returned from a mongoid query.

Place.where({:tags.in => ["food"]}).distinct(:name).limit(2)

But this throws up the following error:

NoMethodError: undefined method 'limit' for ["p1", "p2", "p3", "p4"]:Array

How do I put a limit in the mongoid query instead of fetching the entire result set and then selecting the limited number of items from the array.

Thanks


回答1:


distinct in MongoDB is a command and commands don't return cursors. Only cursors support limit() whereas command results don't, just like sort() isn't supported here, and I think sort is important enough to run first, otherwise you never know which "first two" distinct items you get

There is a way around this, but using the aggregation framework. In plain MongoDB query speak (as you use on the MongoDB shell), you'd use:

db.places.aggregate( [
    { $match: { 'tags' : { $in: [ 'food' ] } } },
    { $group: { '_id': '$name' } },
    { $sort: { 'name': 1 } },
    { $limit: 2 },
] );

In Mongoid I suspect you can change the first line to:

Place.collection.aggregate( [


来源:https://stackoverflow.com/questions/17564357/mongoid-limit-on-distinct-query

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