Skip to content

Commit

Permalink
Merge pull request mongodb#2334 from jpmckinney/min
Browse files Browse the repository at this point in the history
Bug when aggregating on field that doesn't always exist
  • Loading branch information
durran committed Sep 1, 2012
2 parents 68f4555 + 418ae6e commit 7fe4b58
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 3 deletions.
8 changes: 5 additions & 3 deletions lib/mongoid/contextual/aggregable/mongo.rb
Original file line number Diff line number Diff line change
Expand Up @@ -167,10 +167,12 @@ def reducer
function(key, values) {
var agg = { count: 0, max: null, min: null, sum: 0 };
values.forEach(function(val) {
if (agg.max == null || val.max > agg.max) agg.max = val.max;
if (agg.min == null || val.max < agg.min) agg.min = val.max;
if (val.max !== null) {
if (agg.max == null || val.max > agg.max) agg.max = val.max;
if (agg.min == null || val.max < agg.min) agg.min = val.max;
agg.sum += val.sum;
}
agg.count += 1;
agg.sum += val.sum;
});
return agg;
}}
Expand Down
50 changes: 50 additions & 0 deletions spec/mongoid/contextual/aggregable/mongo_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,56 @@
end
end

context "when the field sometimes exists" do
let!(:oasis) do
Band.create(name: "Oasis", likes: 50)
end

let!(:radiohead) do
Band.create(name: "Radiohead")
end

context "and the field doesn't exist on the last document" do
let(:criteria) do
Band.all
end

let(:context) do
Mongoid::Contextual::Mongo.new(criteria)
end

let(:aggregates) do
context.aggregates(:likes)
end

it "returns a min" do
aggregates["min"].should eq(50)
end
end

context "and the field doesn't exist on the before-last document" do
let!(:u2) do
Band.create(name: "U2", likes: 100)
end

let(:criteria) do
Band.all
end

let(:context) do
Mongoid::Contextual::Mongo.new(criteria)
end

let(:aggregates) do
context.aggregates(:likes)
end

it "returns a min" do
aggregates["min"].should eq(50)
end
end
end

context "when there are no matching documents" do

let(:criteria) do
Expand Down

0 comments on commit 7fe4b58

Please sign in to comment.