public
Created

Broken code that should update Mongo document.

  • Download Gist
gistfile1.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
#!/usr/bin/env ruby
 
#
# This is intended to test Mongo's atomic-update operation. It fails; see below.
#
 
require 'mongomatic'
 
class VideoGroup < Mongomatic::Base
 
Mongomatic.db = Mongo::Connection.new.db('mydatabase')
 
end
 
#
# first set up a sample database with a video groups with a couple of videos
#
 
VideoGroup.drop
 
video_group = VideoGroup.new
video_group['videos'] = [
{
'video_id' => 'video1',
},
{
'video_id' => 'video2',
},
]
video_group.insert
 
#
# now update just one video in the video group
#
 
video_group = VideoGroup.find_one('videos.video_id' => 'video1') or raise "Failed to find video group"
 
video_group.update!({ 'videos.video_id' => 'video1' }, '$set' => {
'videos.$.views' => 123,
})
#XXX this fails with 'can't append to array using string field name [$]'
 
#
# finally check to make sure the video got properly updated
#
 
video_group = VideoGroup.find_one('videos.video_id' => 'video1') or raise "Failed to find video group"
video = video_group['videos'].find { |v| v['video_id'] == 'video1' }
raise "Failed to set video attributes" unless video['views'] == 123

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.