diff --git a/lib/mongoid/findable.rb b/lib/mongoid/findable.rb index 34748f7c7e..3d34e1bacc 100644 --- a/lib/mongoid/findable.rb +++ b/lib/mongoid/findable.rb @@ -116,6 +116,36 @@ def exists?(id_or_conditions = :none) with_default_scope.exists?(id_or_conditions) end + # Return true if any documents exist in the criteria. + # + # @example Determine if any documents exist + # Model.any? + # + # @return [ true | false ] If any documents exist. + def any? + limit(1).count > 0 + end + + # Return true if only one document exists in the criteria. + # + # @example Determine if only one document exists + # Model.one? + # + # @return [ true | false ] If only one document exists. + def one? + limit(2).count == 1 + end + + # Return true if more than one document exists in the criteria. + # + # @example Determine if many documents exist + # Model.many? + # + # @return [ true | false ] If many documents exist. + def many? + limit(2).count > 1 + end + # Finds a +Document+ or multiple documents by their _id values. # # If a single non-Array argument is given, this argument is interpreted diff --git a/spec/mongoid/findable_spec.rb b/spec/mongoid/findable_spec.rb index 8e01594410..aba2183285 100644 --- a/spec/mongoid/findable_spec.rb +++ b/spec/mongoid/findable_spec.rb @@ -160,6 +160,84 @@ end end + describe "#any?" do + context "when called on collection with documents" do + before do + Band.create!(name: "Tool") + end + + it "returns true" do + expect(Band.any?).to be true + end + end + + context "when called on collection with no documents" do + + it "returns false" do + expect(Band.any?).to be false + end + end + end + + describe "#one?" do + context "when called on collection with no documents" do + it "returns false" do + expect(Band.one?).to be false + end + end + + context "when called on collection with one document" do + before do + Band.create!(name: "Radiohead") + end + + it "returns true" do + expect(Band.one?).to be true + end + end + + context "when called on collection with multiple documents" do + before do + Band.create!(name: "Tool") + Band.create!(name: "Radiohead") + end + + it "returns false" do + expect(Band.one?).to be false + end + end + + end + + describe "#many?" do + context "when called on collection with no documents" do + it "returns false" do + expect(Band.many?).to be false + end + end + + context "when called on collection with one document" do + before do + Band.create!(name: "Radiohead") + end + + it "returns false" do + expect(Band.many?).to be false + end + end + + context "when called on collection with multiple documents" do + before do + Band.create!(name: "Radiohead") + Band.create!(name: "Tool") + end + + it "returns true" do + expect(Band.many?).to be true + end + end + end + describe "find_by!" do context "when the document is found" do @@ -927,4 +1005,4 @@ expect(User.distinct(:name)).to match_array(['Tom']) end end -end +end \ No newline at end of file