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 文档提到的其余内容。因此,我认为它需要包含包含纬度和经度的文档数组。这也将节省我编写代码的时间。

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

如果有人可以帮助我编写我应该编写的模型结构或指导我参考参考资料,我真的很感激。

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

4

1 回答 1

1

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

如果要嵌入文档,可以使用embedded_many处理此类关系的 mongoid 功能。它还允许您在嵌入式文档上定义索引

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

Mongoid 指出,二维索引应该应用于数组: 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!
于 2015-01-17T10:00:51.167 回答