Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Loading…

Use only one query to count items in a collection #70

Open
wants to merge 1 commit into from

1 participant

Gergő Sulymosi
Gergő Sulymosi

Hi Guys,

Is there a reason for firing 3 queries to count items in a collection?

The previous version caused 3 queries:
1. collection.empty? #=> load an item to ensure there are items in the collection
2. collection.first ... #=> load an item again to be sure about we querying mongo
3. collection.count(true) #=> actual count command

Gergő Sulymosi trekdemo With this approach mongoid will fire only one count query
The previous version caused 3 query:
1. collection.empty? => load an item to ensure there are items in the collection
2. collection.first ... => again load an item to be sure about we querying mongo
3. collection.count(true) => actual count command
3406353
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Commits on Jan 28, 2014
  1. Gergő Sulymosi

    With this approach mongoid will fire only one count query

    trekdemo authored
    The previous version caused 3 query:
    1. collection.empty? => load an item to ensure there are items in the collection
    2. collection.first ... => again load an item to be sure about we querying mongo
    3. collection.count(true) => actual count command
This page is out of date. Refresh to see the latest.
Showing with 3 additions and 1 deletion.
  1. +3 −1 lib/active_admin/mongoid/helpers/collection.rb
4 lib/active_admin/mongoid/helpers/collection.rb
View
@@ -4,13 +4,15 @@ module Collection
alias original_collection_size collection_size
original_collection_size = instance_method(:collection_size)
+
def collection_size(collection=collection)
- if(not collection.empty? and collection.first.class.included_modules.include?(Mongoid::Document))
+ if collection.is_a?(::Mongoid::Criteria)
collection.count(true)
else
original_collection_size(collection)
end
end
+
end
end
end
Something went wrong with that request. Please try again.