Skip to content

Commit

Permalink
MONGOID-5183: Add queries instead of overriding it (#5077)
Browse files Browse the repository at this point in the history
Co-authored-by: Dmitry Rybakov <[email protected]>
  • Loading branch information
sunny4381 and comandeo-mongo authored Nov 8, 2021
1 parent e8356be commit d13ba55
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 1 deletion.
7 changes: 6 additions & 1 deletion lib/mongoid/criteria/queryable/storable.rb
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,12 @@ def add_logical_operator_expression(operator, op_expr)
elsif operator == '$and' || selector.empty?
# $and can always be added to top level and it will be combined
# with whatever other conditions exist.
selector.store(operator, op_expr)
if current_value = selector[operator]
new_value = current_value + op_expr
selector.store(operator, new_value)
else
selector.store(operator, op_expr)
end
else
# Other operators need to be added separately
if selector[operator]
Expand Down
11 changes: 11 additions & 0 deletions spec/integration/criteria/logical_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,17 @@
bands = Band.where(name: /Proj/).and(Band.where(name: /u/))
expect(bands.to_a).to eq([sp])
end

it 'combines existing `$and` clause in query and `where` condition' do
bands = Band.where(id: 1).and({year: {'$in' => [2020]}}, {year: {'$in' => [2021]}}).where(id: 2)
expect(bands.selector).to eq(
{
"_id"=>1,
"year"=>{"$in"=>[2020]},
"$and"=>[{"year"=>{"$in"=>[2021]}}, {"_id"=>2}]
}
)
end
end

describe 'or' do
Expand Down
15 changes: 15 additions & 0 deletions spec/mongoid/criteria/queryable/storable_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,21 @@
end
end

context '$and to query with $and onto query whose first one is not $and' do
let(:query) do
Mongoid::Query.new.where({'foo' => 'baz'}).where('$and' => [{zoom: 'zoom'}])
end

let(:modified) do
query.send(query_method, '$and', [{'foo' => 'bar'}])
end

it 'adds to existing $and' do
modified.selector.should == {
'$and' => [{'zoom' => 'zoom'}, {'foo' => 'bar'}], 'foo' => 'baz'}
end
end

end

context '$or operator' do
Expand Down

0 comments on commit d13ba55

Please sign in to comment.