Skip to content

Commit

Permalink
MONGOID-5632 update_all with atomic operations and aliased fields (#5670
Browse files Browse the repository at this point in the history
) (#5672)

* MONGOID-5632 update_all with atomic operations and aliased fields

* failing specs due to __consolidate__ change

* jruby 9.3 is complaining about #start_with? on a Symbol

* fix failure related to expected arguments
  • Loading branch information
jamis authored Jul 21, 2023
1 parent 767e5ae commit 15bf11c
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 5 deletions.
8 changes: 6 additions & 2 deletions lib/mongoid/extensions/hash.rb
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,12 @@ def __consolidate__(klass)
consolidated = {}
each_pair do |key, value|
if key =~ /\$/
value.each_pair do |_key, _value|
value[_key] = (key == "$rename") ? _value.to_s : mongoize_for(key, klass, _key, _value)
value.keys.each do |key2|
value2 = value[key2]
real_key = klass.database_field_name(key2)

value.delete(key2) if real_key != key2
value[real_key] = (key == "$rename") ? value2.to_s : mongoize_for(key, klass, real_key, value2)
end
consolidated[key] ||= {}
consolidated[key].update(value)
Expand Down
14 changes: 14 additions & 0 deletions spec/mongoid/contextual/mongo_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3576,6 +3576,20 @@
end
end

context 'when using aliased field names' do
before do
context.update_all('$set' => { years: 100 })
end

it "updates the first matching document" do
expect(depeche_mode.reload.years).to eq(100)
end

it "updates the last matching document" do
expect(new_order.reload.years).to eq(100)
end
end

context "when the attributes must be mongoized" do

before do
Expand Down
6 changes: 3 additions & 3 deletions spec/mongoid/extensions/hash_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,7 @@

it "moves the non hash values under the provided key" do
expect(consolidated).to eq({
"$set" => { name: "Tool", likes: 10 }, "$inc" => { plays: 1 }
"$set" => { 'name' => "Tool", likes: 10 }, "$inc" => { 'plays' => 1 }
})
end
end
Expand All @@ -195,7 +195,7 @@

it "moves the non hash values under the provided key" do
expect(consolidated).to eq({
"$set" => { likes: 10, name: "Tool" }, "$inc" => { plays: 1 }
"$set" => { likes: 10, 'name' => "Tool" }, "$inc" => { 'plays' => 1 }
})
end
end
Expand All @@ -213,7 +213,7 @@

it "moves the non hash values under the provided key" do
expect(consolidated).to eq({
"$set" => { likes: 10, name: "Tool" }, "$inc" => { plays: 1 }
"$set" => { likes: 10, name: "Tool" }, "$inc" => { 'plays' => 1 }
})
end
end
Expand Down

0 comments on commit 15bf11c

Please sign in to comment.