2

我已经阅读了 mongoid 文档,但对我正确理解如何正确索引嵌入文档感到不自信。请看一下这个小代码片段,如果我在正确的轨道上,请告诉我!

标准

temp = Array.new
temp.push(BSON::ObjectId("some_bson_objecId"))
temp.push(BSON::ObjectId("some_other_bson_objecId"))
Game.any_of({'players.user_id' => @user.id},{:_id => temp})

游戏模型

embeds_many :players
index(
[
  [ "players.user_id" ],
  [ "players.user_name" ]
],
unique: true
)

播放器型号

embedded_in :game
field :user_id, :type => BSON::ObjectId
field :user_name, :type => String, :default => ""
index(
[
  [ :user_id ],
  [ :user_name ]
],
unique: true
)
4

2 回答 2

0

来自 Mongoid 的文档 -

class Person
  include Mongoid::Document
  embeds_many :addresses
  index "addresses.street" => 1
end

所以试试

class Game 
  include Mongoid::Document
  embeds_many :players 
  index "players.user_id" => 1
  index "players.user_name" => 1
end

class Player
  include Mongoid::Document
  embedded_in :game
  field :user_id
  field :user_name
  index({ user_id: 1, user_name: 1 })
end
于 2013-08-15T18:22:49.567 回答
0

您缺少几件事。

  • 您需要指定索引您选择的每个字段的方向(原因解释here。)

  • 您没有index正确地将参数传递给该方法。相反,第一个参数应该是您要索引的字段的散列,第二个参数应该是选项的散列。

您的代码试图实现的正确语法是这样的:

游戏模型

embeds_many :players
index({ 
    "players.user_id" => 1,
    "players.user_name" => 1
  }, {
    unique: true
})

播放器型号

embedded_in :game
field :user_id, :type => BSON::ObjectId
field :user_name, :type => String, :default => ""
index({
    user_id: 1,
    user_name: 1
  }, {
    unique: true
})

此外,您似乎试图索引的内容超出了您的需要。如果您只是要在games集合中进行搜索,则无需为Player模型中的任何字段建立索引。

相反,您应该只对要查询的字段进行索引。为了正确索引您要查询的信息,您的代码应如下所示:

游戏模型

embeds_many :players
# The field of the 'games' collection that you will be querying for
index({ "players.user_id" => 1 })

播放器型号

embedded_in :game
field :user_id, :type => BSON::ObjectId
field :user_name, :type => String, :default => ""
# No indexing necessary for your player model.

如果您正在执行其他查询,更多索引可能会有所帮助,但请记住,索引是查询时间与空间的权衡。MongoDB 的网站有一些指导方针可以帮助您决定是否应该索引某些内容。另外,请记住,您始终可以在没有索引的情况下查询数据,它只会更慢;)。

于 2017-09-07T21:19:56.420 回答