Mongoid-限制不同查询 [英] Mongoid - limit on distinct query

查看:74
本文介绍了Mongoid-限制不同查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图限制从蒙古式查询返回的不同结果的数量.

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

但这会引发以下错误:

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

如何在蒙古式查询中设置一个限制,而不是获取整个结果集,然后从数组中选择数量有限的项目.

谢谢

解决方案

MongoDB中的distinct是命令,命令不会返回游标.仅游标支持limit(),而命令结果不支持,就像这里不支持sort()一样,我认为sort非常重要,可以首先运行,否则您将永远不知道获得哪个前两个"不同的项目

有一种解决方法,但是可以使用聚合框架.用简单的MongoDB查询语言(如在MongoDB Shell上使用的那样),您将使用:

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

在Mongoid中,我怀疑您可以将第一行更改为:

Place.collection.aggregate( [

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

解决方案

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

这篇关于Mongoid-限制不同查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆