Skip to content

Instantly share code, notes, and snippets.

@jslabovitz
Created October 4, 2012 18:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jslabovitz/3835672 to your computer and use it in GitHub Desktop.
Save jslabovitz/3835672 to your computer and use it in GitHub Desktop.
Broken code that should update Mongo document.
#!/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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment