Skip to content

Instantly share code, notes, and snippets.

@AvnerCohen
Last active December 28, 2015 22:09
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 AvnerCohen/7569229 to your computer and use it in GitHub Desktop.
Save AvnerCohen/7569229 to your computer and use it in GitHub Desktop.
Read, Write and Upsert in mongoid, run: RACK_ENV=development ruby doc.rb
require 'mongoid'
Mongoid.load!("./mongoid.yml")
Mongoid.raise_not_found_error = false
class Doc
include Mongoid::Document
store_in collection: "testing123"
field :name, type: Integer
field :_id, type: Integer, default: ->{ name }
field :somehash, :type => Hash
end
$counter = 0
def printme
entry = Doc.collection.find({:name => 123}).first
p "Found Elem #{$counter = $counter+1}: #{entry.inspect}"
p "Found Hash #{$counter}: #{entry.fetch("somehash", :NoFound)}"
end
#1- Find or Modufy first hash
Doc.collection.find({:name => 123}).remove
a = Doc.find_and_modify({:_id => 123, :name => 123, :somehash => {c: 1} },{upsert: true, new: true})
printme
#2- Create the first entry in the internal hash
a = Doc.collection.find({:name => 123})
a.upsert("$set" => {"somehash.b" => 1})
printme
#3- Update the first entry in the internal hash
a = Doc.collection.find({:name => 123})
a.upsert("$set" => {"somehash.b" => 2})
printme
#4- Add a second entry to somehash
a = Doc.collection.find({:name => 123})
a.upsert("$set" => {"somehash.c" => 1})
printme
development:
sessions:
default:
database: mongoid_dev
hosts:
- localhost:27017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment