views:

154

answers:

2

Hello

I have a projects model with just a name field and in it also the embedded relation to line_items. class Project include mongoid::document field :name embeds_many :line_items end

  class LineItem
   include mongoid::document
   field :title
   embedded_in :project, :inverse_of => :line_items
  end

I suppose this is more of the mongo driver question: if I had such a document

db.project.find()[0]
      {
        _id : 123, 
        name : "housework", 
        line_items:[
         { title : "clean fridge", _id : 601},
         { title : "clean tub",    _id : 602},
         { title : "clean oven",   _id : 603}
        ]
      }
  • 1) How do I update say the line item with id 601 in mongo console?
  • 2) how do I delete it?

Thanks!

A: 

1/ Update :

pro = Project.first
line_item = pro.line_items.find(601)
line_item.title = 'new title'
line_item.save

2/ Delete :

pro = Project.first
line_item = pro.line_items.find(601)
pro.line_item_ids.delete(601)
pro.save
shingara
Thanks Shingara, but this is from Rails Console, not from the MongoDB console. Do you happen to know what the syntax is for mongodb?
Nik
@shingara, for the delete is that the correct third line? in most cases you won't know the ID of the embedded item, so you'd probably do a: line_item = pro.line_items.where(:title => "xxx").first and then a pro.line_item_ids.delete(line_item.id)
Nader
A: 

Try ...

Update:

db.project.update( { line_items._id : 601 }, { $set : { line_items.title : "new title" } })

Delete:

db.project.update( { $pull : { line_items._id : 601 } })

Sorry about that, try it now?

luckytaxi
Thanks Luckytaxi. The update works, but the remove actually removes the project(s) containing a line item with an id 601
Nik