【问题标题】:Embedding Documents Directly in Documents with mongoid使用 mongoid 将文档直接嵌入到文档中
【发布时间】:2011-08-19 10:43:51
【问题描述】:

我需要将嵌入文档数组批量插入到现有文档中。我已经尝试了下面的代码,但它不起作用

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

目前我通过循环数组分别插入每个文档,我希望有更好的清洁方法来做到这一点。

从 mongo shell 我们可以很容易地做到这一点

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

查看link 了解更多信息.. 是否可以使用 mongoid 执行此操作?

【问题讨论】:

    标签: ruby mongodb mongoid


    【解决方案1】:

    原来是赋值后调用save方法有问题

     biz.locations = arr_loc  #this is fine
     biz.save # no need for that
    

    Mongoid 更新作业本身的文档,无需显式保存。请参阅此mongoid google group thread (Thanks Nick hoffman) 了解更多信息

    【讨论】:

      猜你喜欢
      • 2023-03-07
      • 2011-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多