LoginSignup
3

More than 5 years have passed since last update.

MongoDB 3.4でcollation(照合順序)を試してみた

Last updated at Posted at 2016-09-27

MongoDB 3.41からcollation(照合順序)機能が追加された。
collationというのは、文字列を比較したりソートしたりするときに、言語特有のルールにしたがって比べられるようにするためのもの。MySQLやSQL Serverにも似たような機能がある。

日本語サポートは?

対応済み。
https://docs.mongodb.com/master/reference/collation-locales-defaults/#collation-languages-locales

内部でICU4Cを使っており、ICU 57.1で対応されているすべてのcollationに対応済みということらしい。

We now support all collations that are supported by ICU
57.1, except for aliases. See the SERVER ticket for a list
of the new locales. The exact ICU data files which we now
package into MongoDB is given by COLLATION_SOURCE in ICU
57.1's colfiles.mk.

デフォルト

デフォルトは無指定(localeすら何も指定が無い状態)、すなわちsimple binary collationとなる。以前のバージョンと同じ。

設定タイミング

collection作成時、index作成時、さらに、find()など各CRUD系メソッド、aggregateなどに対して設定可能。
https://docs.mongodb.com/master/reference/collation/#operations-that-support-collation

collectionに対して設定しておくと、indexや各メソッドでは、別途指定がない限り、collectionでの設定がそのまま適用される。

Collation Document(設定パラメータ)

collationは、単にlocaleを指定できるだけではなく、以下の8つのパラメータを使うことができる。このまとまりをCollation Documentという。localeだけが必須で、他は任意。

{
   locale: <string>,
   caseLevel: <boolean>,
   caseFirst: <string>,
   strength: <int>,
   numericOrdering: <boolean>,
   alternate: <string>,
   maxVariable: <string>,
   backwards: <boolean>
}

strength (Comparison Level)

比較のレベル。アクセントのありなしまで考慮して比べるか、大文字小文字の区別までするか、など。デフォルトは3(文字の違い、アクセントありなし、大文字小文字まで区別)
https://docs.mongodb.com/manual/release-notes/3.3-dev-series-collation/#collation-option
http://userguide.icu-project.org/collation/concepts#TOC-Comparison-Levels

strength 4

日本語の場合4が重要のようで、ひらがな<カタカナとするためには4を指定する必要がありそうなことが書いてある。
http://userguide.icu-project.org/collation/concepts#TOC-Comparison-Levels

Hiragana symbols are given smaller values than Katakana symbols on quaternary level, thus causing Hiragana sequences to sort before corresponding Katakana sequences.

'ハハ'='パパ' 問題

ぱっと見うまくいってそうだったけどログ取ってないので後で書く。
MySQLのutf8_unicode_ciでの問題はlevel 1までしか実装していないことが原因らしいので、Mongoが全レベル実装できているとすれば問題ないはずと期待したい。

寿司ビール問題

これも後で。

ひとまず。


  1. 正確には開発版である3.3から。MongoDBのバージョンは、小数点以下第一位が奇数が開発版、偶数が安定板の扱い。 

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
What you can do with signing up
3