LoginSignup
15
10

More than 5 years have passed since last update.

Mongoidからインデックスを操作する

Last updated at Posted at 2016-03-29

MongoDBのインデックスをMongoidから個別に削除する方法を調べたので、これを期にMongoid経由でのインデックス操作をまとめておく。

モデル全体

rakeタスクが用意されているのそれを使う

bundle exec rake db:mongoid:create_indexes
bundle exec rake db:mongoid:remove_indexes

単一のモデルに対して

ここからはrails cとかで。

Account.create_indexes
Account.remove_indexes

インデックスを個別に削除したい場合

まずは既存のインデックス一覧を取得。

Account.collection.indexes.to_a

こんな結果が帰ってくる。

[{"v"=>1, "key"=>{"_id"=>1}, "name"=>"_id_",    "ns"=>"database_name.accounts"},
 {"v"=>1, "key"=>{"name"=>1}, "name"=>"name_1", "background"=>true, "ns"=>"database_name.accounts"},
{"v"=>1, "key"=>{"email"=>1}, "name"=>"email_1", "background"=>true, "ns"=>"database_name.accounts"}]

削除したいkeyを指定してdrop_oneを呼べばOK。

Account.collection.indexes.drop_one({"name"=>1})
15
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
10