5

我有一个只有名称字段的项目模型,其中还有与 line_items 的嵌入关系。类项目包括 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)如何删除它?

谢谢!

4

4 回答 4

15

当前 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)) 一起使用的变体,但这些变体似乎没有任何效果。

于 2011-04-01T01:24:38.533 回答
1

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
于 2010-09-12T13:18:36.453 回答
0

尝试 ...

更新:

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

删除:

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

抱歉,现在试试?

于 2010-09-13T13:41:04.753 回答
0

尝试:

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

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

于 2012-11-25T22:04:14.650 回答