对单个字段创建通配符索引
单个字段上的通配符索引支持对索引字段的任何子字段进行查询。 使用通配符索引来支持对事先不知道或因文档而异的字段名称的查询。
要在单个字段上创建通配符索引,请使用 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
或其嵌入式字段进行单字段查询。 示例,该索引支持以下查询:
query:
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' } } } ] query:
db.products.find( { "attributes.material" : "Leather" } ) 输出:
[ { _id: ObjectId("63472196b1fac2ee2e957ef6"), product_name: 'Spy Coat', attributes: { material: [ 'Tweed', 'Wool', 'Leather' ], size: { length: 72, units: 'inches' } } } ] query:
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
)时,通配符索引具有特定行为。 有关详细信息,请参阅嵌入式对象和数组上的通配符索引。
了解详情
要学习;了解有关通配符索引的行为和使用案例的更多信息,请参阅: