cfpete cfpete - 3 months ago 17
Ruby Question

how to use ruby's mongo driver to update a mult-level document

How do I use the ruby's mongo driver to update a multi-level document. For example, here's part of the docuement:

"group_overrides": [
"additional_filesystem_gb": 0,
"components": [
"comp": "jbosseap-6",
"cart": "jbosseap-6",
"cart_id": ObjectId("5423d363f4b25eea0b000021")
"max_gears": 1

In the mongo-shell I can do something like:

db.applications.update({name:"ulmuqhfv"}, {$set: {"group_overrides.0.additional_filesystem_gb": 1}})

and the document will be updated. When I tried the following:

db.update('applications', {"app_name"=>"ulmuqhfv"}, {"$set"=>{"group_overrides.0.additional_filesystem_gb"=>1})

It failed. What's the correct syntax for updating an array?

db is an instance of a wrapper class around the ruby mongo driver. Here's what the update method looks like:

def update(c_name, selector, opts)
db = @db.collection(c_name)
if opts
db.update(selector, opts).to_a


as simple as that:

db['applications'].update({"app_name"=>"ulmuqhfv"}, {"$set"=>{"group_overrides.0.additional_filesystem_gb"=>1})

you need to access your collection as you access hash keys, db['applications'] will return the collection object

mongo_connection ="localhost", 27017) # your connection settings
db = mongo_connection.db("mydb") # select database
coll = db['applications'] # select collection
coll.update({"app_name"=>"ulmuqhfv"}, {"$set"=>{"group_overrides.0.additional_filesystem_gb"=>1})

you can learn more here under Getting a Collection section