Nik So
Nik So

Reputation: 16821

remove an embedded document in mongoid

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}
        ]
      }

Thanks!

Upvotes: 5

Views: 10379

Answers (4)

Anand Nandakumar
Anand Nandakumar

Reputation: 122

Try:

db.project.update({}, {$set: {line_items: []}});

to remove embedded documents, this will only reset the data inside it to empty but will still retain an empty object in the db which you can repopulate later on.

Upvotes: 0

Hollownest
Hollownest

Reputation: 1067

Current Mongoid (2.0.0) allows:

@category = @list.categories.find(params[:id])
@category.delete

And the resulting database query/update looks like:

MONGODB test['lists'].update({"_id"=>BSON::ObjectId('4d9522315569b11918000019')}, {"$pull"=>{"categories"=>{"_id"=>BSON::ObjectId('4d9523e05569b1191800001f')}}})

Also see the last example on http://mongoid.org/docs/persistence/

Note, I tried variations on this that would have worked with ActiveRecord (@list.categories.delete(xx)) and those do not seem to have any effect.

Upvotes: 15

sdot257
sdot257

Reputation: 10376

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?

Upvotes: 0

shingara
shingara

Reputation: 46914

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

Upvotes: 1

Related Questions