对所有字段创建通配符索引
您可以创建通配符索引,以支持对所有可能的文档字段进行查询。 通配符索引支持对任意或未知字段名称进行查询。
要在所有字段(不包括 _id
)上创建通配符索引,请使用通配符说明符 ( $**
) 作为索引键:
db.<collection>.createIndex( { "$**": <sortOrder> } )
关于此任务
仅当要索引的字段未知或可能更改时,才使用通配符索引。 通配符索引的性能不如特定字段上的定向索引。 如果您的集合包含阻止目标索引的任意字段名称,请考虑重新建模您的模式以具有一致的字段名称。 要学习;了解有关目标索引的更多信息,请参阅创建索引以支持查询。
开始之前
创建包含以下文档的artwork
collection:
db.artwork.insertMany( [ { "name": "The Scream", "artist": "Edvard Munch", "style": "modern", "themes": [ "humanity", "horror" ] }, { "name": "Acrobats", "artist": { "name": "Raoul Dufy", "nationality": "French", "yearBorn": 1877 }, "originalTitle": "Les acrobates", "dimensions": [ 65, 49 ] }, { "name": "The Thinker", "type": "sculpture", "materials": [ "bronze" ], "year": 1904 } ] )
每个文档都包含有关艺术品的详细信息。 字段名称因文档而异,具体取决于作品的可用信息。
步骤
以下操作在artwork
collection(不包括_id
)中的所有文档字段上创建通配符索引:
db.artwork.createIndex( { "$**" : 1 } )
结果
该索引支持对collection中任意字段进行单字段查询。如果文档包含嵌入式文档或数组,则通配符索引会遍历文档或数组,并将所有字段的值存储在文档或数组中。
例如,该索引支持以下查询:
query:
db.artwork.find( { "style": "modern" } ) 输出:
[ { _id: ObjectId("6352c401b1fac2ee2e957f09"), name: 'The Scream', artist: 'Edvard Munch', style: 'modern', themes: [ 'humanity', 'horror' ] } ] query:
db.artwork.find( { "artist.nationality": "French" } ) 输出:
[ { _id: ObjectId("6352c525b1fac2ee2e957f0d"), name: 'Acrobats', artist: { name: 'Raoul Dufy', nationality: 'French', yearBorn: 1877 }, originalTitle: 'Les acrobates', dimensions: [ 65, 49 ] } ] query:
db.artwork.find( { "materials": "bronze" } ) 输出:
[ { _id: ObjectId("6352c387b1fac2ee2e957f08"), name: 'The Thinker', type: 'sculpture', materials: [ 'bronze' ], year: 1904 } ]
了解详情
要了解如何创建投影特定字段以覆盖的通配符索引,请参阅以下页面:
要了解有关通配符索引行为的更多信息,请参阅: