Mongo_mapper limit results

牧云@^-^@ 提交于 2019-12-05 18:24:17

For me it seems logical to start my clauses with the where, and narrow them down further, or modify them… In MongoMapper, I find querying rigor is much more “loose” than say a SQL SELECT query that requires things in proper order… I would tend to write my queries in more or less this fashion:

ModelClass.where(some criteria).[sort | order | another where clause | fields | limit].[all | first | paginate]

In addition, it is important to note that MongoMapper returns a query and does not actually perform the query until you add something that needs the results. For example: all, first, paginate, sort, etc.

2.0.0-p247 :001 > Structure.where(:address => /NJ/).count
 => 22 
2.0.0-p247 :002 > Structure.where(:address => /NJ/).limit(2).count
 => 22 
2.0.0-p247 :003 > Structure.where(:address => /NJ/).limit(2).all.count
 => 2 

More details here: http://technicaldebt.com/mongomapper-query-review/ and for the underlying Plucky query syntax, here: https://github.com/mongomapper/plucky

The problem is that count() and limit() for a MongoDB cursor do not interact the way you are anticipating.

By default a cursor.count() shows the number of documents referenced by a cursor, but it doesn't take into account the limit.

The cursor.limit() option determines the maximum number of documents that will be returned by the cursor.

If you are querying via the mongo shell you can use cursor.count(true) to have count() respect the limit. I suspect this may work in MongoMapper as well.

I would also try your where() query with a smaller restriction like limit(5) so you can more easily confirm the limit is working as expected when you print the results.

If I try to run Job.all(query).limit(100) I get "undefined method limit for Array #foo"

MongoMapper's all() returns the results as an array, so it is too late to apply the limit for the cursor since the documents are already fetched.

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