首页 文章

如何使用包含另一个文档的数组字段创建模型作为Mongodb中的嵌入文档(Mongoid)

提问于
浏览
1

我正在使用Rails 4和Mongoid作为基于事件的应用程序 . 我正在尝试创建一个模型,我想在该数组中添加一个包含嵌入文档的数组字段 . 此嵌入文档将包含用户的地理坐标和时间戳 . 每隔5分钟,我会将用户的最新坐标推送到用户(位置)数组 . 有人可以帮助我,我怎样才能创造它 .

我的样本模型和所需文档如下 .

class User
  include Mongoid::Document
  field :name, type: String

  field :locations, type: Array

end

在这里,我想推动

这是我要查找的示例文档:

{ _id : ObjectId(...),
  name : "User_name",
  locations : [ {
                 _id : ObjectID(...),
                 time : "...." ,
                 loc : [ 55.5, 42.3 ]
                } ,
                {
                 _id : ObjectID(...),
                 time : "...",
                 loc : [ -74 , 44.74 ]
                }
              ]
}

我能够通过IRB在没有嵌入文档的位置数组中添加值,但是我将在稍后使用MongoDB的地理空间查询,所以我想使用2D索引以及Mongo Documentation提到的其他东西 . 因此,我认为它需要包含纬度和经度的文档数组 . 这也将节省我的代码时间 .

我也可以将位置的时间作为文件“_id”吗? (它可以帮助我减少查询开销)

如果有人可以帮我解决模型的结构,我应该写一下或引导我参考 .

P.S:如果你建议一些关于在mongoDB中存储地理空间数据的额外参考/帮助,请告诉我,这对我有帮助 .

1 回答

  • 0

    希望这会对某人有所帮助 .

    如果要嵌入文档,可以使用mongoid的 embedded_many 功能来处理这种关系 . 它还允许您定义嵌入文档的索引

    http://mongoid.org/en/mongoid/docs/relations.html#embeds_many

    Mongoid指出,2D索引应该应用于数组:http://mongoid.org/en/mongoid/docs/indexing.html

    在您的情况下,模型可能如下所示:

    class User
      include Mongoid::Document
    
      field :name, type: String
    
      embeds_many :locations
    
      index({ "locations.loc" => "2d" })
    
      accepts_nested_attributes_for :locations # see http://mongoid.org/en/mongoid/docs/nested_attributes.html#common
    end
    
    class Location
      include Mongoid::Document
    
      field :time, type: DateTime # see http://mongoid.org/en/mongoid/docs/documents.html#fields
      field :loc, type: Array
    
      embedded_in :user
    end
    

    但要注意使用 update 和嵌套属性 - 它只允许您更新属性,但不能删除或拒绝它们 . 最好使用 (association)_attributes= 方法:

    @user = User.new({ name: 'John Doe' })
    @user.locations_attributes = {
      "0" => {
       _id : ObjectID(...),
       time : "...." ,
       loc : [ 55.5, 42.3 ]
      } ,
      "1" => {
       _id : ObjectID(...),
       time : "...",
       loc : [ -74 , 44.74 ]
      }
    }
    @user.save!
    

相关问题