【问题标题】:Indexing mongoid索引 mongoid
【发布时间】:2012-05-02 21:33:42
【问题描述】:

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

标准

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
)

【问题讨论】:

    标签: mongoid


    【解决方案1】:

    来自 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
    

    【讨论】:

      【解决方案2】:

      您缺少一些东西。

      • 您需要指定索引您选择的每个字段的方向(原因解释了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 的网站上有一些guidelines 可以帮助您决定是否应该索引某些内容。另外,请记住,您始终可以在没有索引的情况下查询数据,它只会更慢;)。

      【讨论】:

        猜你喜欢
        • 2023-03-26
        • 2019-08-01
        • 1970-01-01
        • 1970-01-01
        • 2021-01-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多