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 @   wongchaofan  阅读(9)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示