[MongoDB] index 名の長さは最大 127 byte までしか設定できない

MongoDB の index 名は最大 127 byte までしか設定できません。

MongoDB | モンゴディービー

MongoDB の index 名の長さについて

MongoDB の公式ドキュメントによると index 名は最大 127 文字までと明記されており、128 文字以上は設定できないとのことです。

Index Name Length

Fully qualified index names, which includes the namespace and the dot separators (i.e. ..$), cannot be longer than 128 characters.

MongoDB index 名が長すぎてエラーになった場合

> db.users.createIndex( { email: 1 } , { name: "01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345" } )
{
	"ok" : 0,
	"errmsg" : "namespace name generated from index name \"test.users.$01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345\" is too long (127 byte max)",
	"code" : 67
}

MongoDB index 名の長さが OK で index が作成できた場合

db name, collection name, あと . や $ などを含めて、index name が 127 文字以内なら、正常に index を作成できます。

> db.users.createIndex( { email: 1 } , { name: "0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234" } )
{
	"createdCollectionAutomatically" : false,
	"numIndexesBefore" : 1,
	"numIndexesAfter" : 2,
	"ok" : 1
}

単一 field に index を作成するときは index 名のことは特に気にする必要はありません。

複合 index を作成するときはデフォルトの場合 field 名が長くなりがちなので、index 名についても少し気にしておいた方がよさそうです。

以上、MongoDB の index 名の最大長が気になって調査した現場からお送りしました。