lib/mongoid/contextual/mongo.rb in mongoid-8.0.6 vs lib/mongoid/contextual/mongo.rb in mongoid-8.0.7

- old
+ new

@@ -54,11 +54,16 @@ # into the count. # # @return [ Integer ] The number of matches. def count(options = {}, &block) return super(&block) if block_given? - view.count_documents(options) + + if valid_for_count_documents? + view.count_documents(options) + else + view.count(options) + end end # Get the estimated number of documents matching the query. # # Unlike count, estimated_count does not take a block because it is not @@ -810,9 +815,27 @@ docs = raw_docs.map do |d| Factory.from_db(klass, d, criteria) end docs = eager_load(docs) limit ? docs : docs.first + end + + # Queries whether the current context is valid for use with + # the #count_documents? predicate. A context is valid if it + # does not include a `$where` operator. + # + # @return [ true | false ] whether or not the current context + # excludes a `$where` operator. + def valid_for_count_documents?(hash = view.filter) + # Note that `view.filter` is a BSON::Document, and all keys in a + # BSON::Document are strings; we don't need to worry about symbol + # representations of `$where`. + hash.keys.each do |key| + return false if key == '$where' + return false if hash[key].is_a?(Hash) && !valid_for_count_documents?(hash[key]) + end + + true end end end end