删除mongoid中的嵌入文档

我有一个只带有名称字段的项目模型,还有与line_items的嵌入关系。 class Project包含mongoid :: document字段:name embeds_many:line_items end

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

我想这更像是mongo驱动程序的问题:如果我有这样的文件

 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)如何更新在mongo控制台中说出ID为601的订单项?
  • 2)如何删除它?

谢谢!

当前的Mongoid(2.0.0)允许:

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

结果数据库查询/更新如下所示:

MONGODB test [‘lists’]。update({“_ id”=> BSON :: ObjectId(’4d9522315569b11918000019’)},{“$ pull”=> {“categories”=> {“_ id”=> BSON :: ObjectId ( ‘4d9523e05569b1191800001f’)}}})

另请参阅http://mongoid.org/docs/persistence/上的最后一个示例

请注意,我尝试过使用ActiveRecord(@ list.categories.delete(xx))的变体,这些似乎没有任何效果。

1 /更新:

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

2 /删除:

 pro = Project.first line_item = pro.line_items.find(601) pro.line_item_ids.delete(601) pro.save 

试试……

更新:

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

删除:

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

对不起,现在试试吧?

尝试:

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

要删除嵌入的文档,这只会将其中的数据重置为空,但仍会在数据库中保留一个空对象,以后可以重新填充。