lib/mongoid/contextual/mongo.rb in mongoid-7.1.11 vs lib/mongoid/contextual/mongo.rb in mongoid-7.2.0.rc1

- old
+ new

@@ -69,13 +69,32 @@ # @return [ Integer ] The number of matches. # # @since 3.0.0 def count(options = {}, &block) return super(&block) if block_given? - try_cache(:count) { view.count(options) } + try_cache(:count) { view.count_documents(options) } end + # Get the estimated number of documents matching the query. + # + # Unlike count, estimated_count does not take a block because it is not + # traditionally defined (with a block) on Enumarable like count is. + # + # @example Get the estimated number of matching documents. + # context.estimated_count + # + # @param [ Hash ] options The options, such as maxTimeMS to be factored + # into the count. + # + # @return [ Integer ] The number of matches. + def estimated_count(options = {}) + unless self.criteria.selector.empty? + raise Mongoid::Errors::InvalidEstimatedCountCriteria.new(self.klass) + end + try_cache(:estimated_count) { view.estimated_document_count(options) } + end + # Delete all documents in the database that match the selector. # # @example Delete all the documents. # context.delete # @@ -256,16 +275,16 @@ # @since 3.0.0 def first(opts = {}) return documents.first if cached? && cache_loaded? try_cache(:first) do if sort = view.sort || ({ _id: 1 } unless opts[:id_sort] == :none) - if raw_doc = view.sort(sort).limit(-1).first + if raw_doc = view.sort(sort).limit(1).first doc = Factory.from_db(klass, raw_doc, criteria) eager_load([doc]).first end else - if raw_doc = view.limit(-1).first + if raw_doc = view.limit(1).first doc = Factory.from_db(klass, raw_doc, criteria) eager_load([doc]).first end end end @@ -370,10 +389,10 @@ # # @since 3.0.0 def last(opts = {}) try_cache(:last) do with_inverse_sorting(opts) do - if raw_doc = view.limit(-1).first + if raw_doc = view.limit(1).first doc = Factory.from_db(klass, raw_doc, criteria) eager_load([doc]).first end end end