Embedding Documents Directly in Documents with mongoid

20 views
Skip to first unread message

RameshVel

unread,
Aug 19, 2011, 9:29:47 AM8/19/11
to Mongoid
I need to to bulk insert the array of embedded documents to an
existing document. I have tried the below code, but it was not working

arr_loc = []
arr_loc << Location.new(:name=> "test") << Location.new(:name=>
"test2")
biz = Business.first
biz.locations = arr_loc
biz.loc.save # not working
currently i am inserting each doc separately by looping the array, i
hope there is a better cleaner way to do this.

from mongo shell we can easily do this like this

> var mongo = db.things.findOne({name:"mongo"});
> print(tojson(mongo));
{"_id" : "497da93d4ee47b3a675d2d9b" , "name" : "mongo", "type" :
"database"}
> mongo.data = { a:1, b:2};
{"a" : 1 , "b" : 2}
> db.things.save(mongo);
> db.things.findOne({name:"mongo"});
{"_id" : "497da93d4ee47b3a675d2d9b" , "name" : "mongo" , "type" :
"database", "data" : {"a" : 1 , "b" : 2}}
>
check the link
http://www.mongodb.org/display/DOCS/Updating+Data+in+Mongo#UpdatingDatainMongo-EmbeddingDocumentsDirectlyinDocuments
for more info.. is it possible to do this with mongoid?

Cheers

Nick Hoffman

unread,
Aug 19, 2011, 10:06:48 AM8/19/11
to mon...@googlegroups.com
Hi there, Ramesh.


On Friday, August 19, 2011 9:29:47 AM UTC-4, RameshVel wrote:
I need to to bulk insert the array of embedded documents to an
existing document. I have tried the below code, but it was not working

 arr_loc = []
 arr_loc << Location.new(:name=> "test") << Location.new(:name=>
"test2")
 biz = Business.first
 biz.locations = arr_loc
 biz.loc.save # not working

What is "biz.loc"?

RameshVel

unread,
Aug 19, 2011, 10:17:50 AM8/19/11
to Mongoid
sorry Nick, thats a typo, it is actually biz.save

Cheers

Nick Hoffman

unread,
Aug 19, 2011, 10:38:49 AM8/19/11
to mon...@googlegroups.com
Hrm, assigning an array to the business' "locations" relation automatically updates the business' locations, so there's no need to save the business. Also, I can't reproduce the problem:

class Business
  include Mongoid::Document
  embeds_many :locations
end

class Location
  include Mongoid::Document
  field :name, :type => String
  embedded_in :business
end

Business.delete_all
Business.create


arr_loc = []
arr_loc << Location.new(:name=> "test") << Location.new(:name=> "test2")

biz = Business.first
biz.locations = arr_loc

Business.first.locations
=> [#<Location _id: 4e4e75252b58af429200000e, _type: nil, name: "test">, #<Location _id: 4e4e75252b58af429200000f, _type: nil, name: "test2">]

RameshVel

unread,
Aug 19, 2011, 11:04:12 AM8/19/11
to Mongoid
Thanks Nick, you nailed it. calling 'save' after the assignment is the
problem.. now its working fine

Cheers
Reply all
Reply to author
Forward
0 new messages