问题
I have a query like this:
@allJobs = Job.where(:merchant_id => session[:admin_id].to_s).sort(:start_date.desc).limit(100)
When I run .count on this I get:
jobs count 1720
I expect to see :
jobs count 100
What am I doing wrong?
If I try to run Job.all(query).limit(100) I get "undefined method limit for Array #foo"
It seems there is no way I can get the results to restrict to 100 records sorted in descending order by start_date!
UPDATE:
I cannot even do something simple like this:
@allJobs = Job.limit(100)
Rails.logger.info("@allJobs count is " + @allJobs.count.to_s)
Console:
@allJobs count is 2080
.limit() is completely useless as far as I can tell.
回答1:
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
回答2:
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.
来源:https://stackoverflow.com/questions/20778135/mongo-mapper-limit-results