Mongoid - limit on distinct query

2019-07-07 06:13发布

问题:

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( [