1 つのフィールドにワイルドカード インデックスを作成する
単一フィールドのワイルドカード インデックスは、インデックス フィールドの任意のサブフィールドに対するクエリをサポートします。 ワイルドカードを使用すると、事前に不明なフィールド名やドキュメント間で異なるフィールド名に対するクエリをサポートできます。
単一フィールドにワイルドカード インデックスを作成するには、 db.collection.createIndex()
メソッドを使用し、 インデックス キーにワイルドカード指定子( $**
)を含めます。
db.collection.createIndex( { "<field>.$**": <sortOrder> } )
このタスクについて
ワイルドカード インデックスは、インデックスを作成するフィールドが不明または変更される可能性がある場合にのみ使用してください。ワイルドカード インデックスは、特定のフィールドに対象を絞ったインデックスほどパフォーマンスが良くありません。対象を絞ったインデックスを作成できないような任意のフィールド名がコレクションに含まれている場合は、一貫したフィールド名になるようにスキーマを改造することを検討してください。対象を絞ったインデックスの詳細については、「クエリをサポートするインデックスの作成」を参照してください。
始める前に
次のドキュメントを含むproducts
コレクションを作成します。
db.products.insertMany( [ { "product_name" : "Spy Coat", "attributes" : { "material" : [ "Tweed", "Wool", "Leather" ], "size" : { "length" : 72, "units" : "inches" } } }, { "product_name" : "Spy Pen", "attributes" : { "colors" : [ "Blue", "Black" ], "secret_feature" : { "name" : "laser", "power" : "1000", "units" : "watts", } } } ] )
手順
次の操作を実行すると、attributes
フィールドでワイルドカード インデックスが作成されます。
db.products.createIndex( { "attributes.$**" : 1 } )
結果
ワイルドカード インデックスは、 attributes
またはその埋め込みフィールドに対する単一フィールド クエリをサポートしています。 たとえば、 インデックスは次のクエリをサポートしています。
クエリ:
db.products.find( { "attributes.size.length" : { $gt : 60 } } ) 出力:
[ { _id: ObjectId("63472196b1fac2ee2e957ef6"), product_name: 'Spy Coat', attributes: { material: [ 'Tweed', 'Wool', 'Leather' ], size: { length: 72, units: 'inches' } } } ] クエリ:
db.products.find( { "attributes.material" : "Leather" } ) 出力:
[ { _id: ObjectId("63472196b1fac2ee2e957ef6"), product_name: 'Spy Coat', attributes: { material: [ 'Tweed', 'Wool', 'Leather' ], size: { length: 72, units: 'inches' } } } ] クエリ:
db.products.find( { "attributes.secret_feature.name" : "laser" }, { "_id": 0, "product_name": 1, "attributes.colors": 1 } ) 出力:
[ { product_name: 'Spy Pen', attributes: { colors: [ 'Blue', 'Black' ] } } ]
ワイルドカード インデックスは、インデックス フィールドに埋め込みオブジェクト(たとえばattributes.secret_feature
)が含まれている場合に特定の動作をします。 詳細については、「埋め込みオブジェクトと配列のワイルドカード インデックス 」を参照してください。
詳細
ワイルドカード インデックスの動作とユースケースの詳細については、以下を参照してください。