mongo索引类型

要创建单字段索引,请使用以下原型:

db.<collection>.createIndex( { <field>: <sortOrder> } )

复合索引

要创建复合索引,请使用下列 db.collection.createIndex()方法:

 

db.<collection>.createIndex( {
   <field1>: <sortOrder>,
   <field2>: <sortOrder>,
   ...
   <fieldN>: <sortOrder>
} )

例如,索引支持以下查询:

索引以升序 ( 1) 或降序 ( -1) 顺序存储对字段的引用。对于复合索引排序顺序可以确定索引是否支持排序操作

例子

 考虑leaderboard包含以下文档的集合:
db.leaderboard.insertMany( [
   {
      "score": 50,
      "username": "Alex Martin",
      "date": ISODate("2022-03-01T00:00:00Z")
   },
   {
      "score": 55,
      "username": "Laura Garcia",
      "date": ISODate("2022-03-02T00:00:00Z")
   },
   {
      "score": 60,
      "username": "Alex Martin",
      "date": ISODate("2022-03-03T00:00:00Z")
   },
   {
      "score": 60,
      "username": "Riya Patel",
      "date": ISODate("2022-03-04T00:00:00Z")
   },
   {
      "score": 50,
      "username": "Laura Garcia",
      "date": ISODate("2022-03-05T00:00:00Z")
   }
] )

此查询返回排行榜结果:

db.leaderboard.find().sort( { score: -1, username: 1 } )

多键索引

要创建多键索引,请使用以下原型:

db.<collection>.createIndex( { <arrayField>: <sortOrder> } )

创建文本索引

要创建文本索引,请使用方法db.collection.createIndex() 。要索引包含字符串或字符串元素数组的字段,请指定字符串"text"作为索引键:

db.<collection>.createIndex(
   {
      <field1>: "text",
      <field2>: "text",
      ...
   }
)

一个集合最多可以有一个文本索引。

您可以在单个文本索引中索引多个字段。文本索引最多可包含 32 个字段。

db.blog.createIndex( { "content": "text" } )
db.blog.find(
   {
      $text: { $search: "coffee" }
   }
)

输出:

[
   {
     _id: 1,
     content: 'This morning I had a cup of coffee.',
     about: 'beverage',
     keywords: [ 'coffee' ]
   },
   {
     _id: 3,
     content: 'My favorite flavors are strawberry and coffee',
     about: 'ice cream',
     keywords: [ 'food', 'dessert' ]
   }
]

 指定文本索引的默认语言

 默认情况下,文本索引的default_language 为english。为了提高非英语文本搜索查询的性能,您可以指定与文本索引关联的其他默认语言。

db.<collection>.createIndex(
   { <field>: "text" },
   { default_language: <language> }
)

 

 

 

 

 

posted @ 2024-07-18 18:21  wongchaofan  阅读(2)  评论(0编辑  收藏  举报