Embedding documents in existing documents with the Ruby Driver for MongoDB

451 views Asked by At

I'm trying to embed a document inside an existing document using the Ruby Driver.

Here's what my primary document looks like:

db = Mongo::Connection.new.db("Portfolios")
project_collection = db.collection("Projects")
new_Project = { :url => 'http://www.tekfolio.me/billy/portfolio/focus', :author => 'Billy'}
project_collection.insert(new_Project)

After I've created my new_project and added it to my project_collection I may or may not add another collection to the same document later called assets. This is where I'm stuck. The following code doesn't seem to do anything:

new_asset = { :image_url => 'http://assets.tekfolio.me/portfolios/68fbb25a-8353-41a8-a779-4bd9762b00f2/projects/13/assets/20/focus2.PNG'}
new_Project.assest.insert(new_asset)

I'm certain I've butchered my understanding of Mongodb and the Ruby driver and the embeded document concept and would appreciate your help getting me out of this wet paper bag I can't seem to get out of ;)

2

There are 2 answers

1
allingeek On BEST ANSWER

Have you tried just setting the value of asset without insert and instead using update?

new_Project["asset"] = new_asset
project_collection.update({"_id" => new_Project["_id"]}, new_Project)
0
Polo Ornelas On

I think , are you trying to "update" the new_project record with the asset

it doesn't work because then you are only updating the hash in ruby, not in mongo, you have to first get the reference to the object in mongo, update it, and then save it, check this info:

http://www.mongodb.org/display/DOCS/Updating+Data+in+Mongo

(if you can, you can assign the asset before inserting, and it should work)