2.5.5 MongoDB -- 聚合
- 排序
- 索引類型
- 建立索引
// 升序
db.getCollection('author').find({}).sort({"age": 1}).limit(20)
// 降序
db.getCollection('author').find({}).sort({"age": -1}).limit(20)
// 組合
db.getCollection('author').find({}).sort({"age": 1, "name": -1}).limit(20)
- 單鍵索引
- 複合索引
- 多鍵索引
- 地理空間索引
- 文本索引
- 索引屬性
- 唯一索引
- TTL索引
- 不區分大小寫索引
- 稀疏索引
- 部分索引
// 使用 explan 檢視 mongo 查詢過程中的執行情況
db.author.find({"name": "user1"}).explain("executionStats")
// 建立索引,-1 代表降序方式建立
db.collection.createIndex( { name: -1 } )
// 複合索引
db.products.createIndex( { "item": 1, "stock": 1 } )
//多鍵索引
{ _id: 1, item: "ABC", ratings: [ 2, 5, 9 ] }
db.survey.createIndex( { ratings: 1 } )
//地理空間索引
db.places.insert(
{
loc : { type: "Point", coordinates: [ -73.97, 40.77 ] },
name: "Central Park",
category : "Parks"
}
)
db.places.createIndex( { loc : "2dsphere" } )
//文本索引,一個集合隻能建立一個
db.reviews.createIndex( { comments: "text" } )
db.reviews.createIndex(
{
subject: "text",
comments: "text"
}
)
// 索引屬性(唯一索引)
db.members.createIndex( { "user_id": 1 }, { unique: true } )
// 索引屬性(TTL索引),可以設定過期時間
db.eventlog.createIndex( { "lastModifiedDate": 1 }, { expireAfterSeconds: 3600 } )
// 索引屬性(不區分大小寫索引)
db.collection.createIndex( { "key" : 1 },
{ collation: {
locale : <locale>,
strength : <strength>
}
} )
// 索引屬性(稀疏索引)
db.addresses.createIndex( { "xmpp_id": 1 }, { sparse: true } )
// 索引屬性(部分索引)
db.restaurants.createIndex(
{ cuisine: 1, name: 1 },
{ partialFilterExpression: { rating: { $gt: 5 } } }
)
```
覆寫索引:所有查詢字段是索引的一部分,所有查詢傳回字段在同一個索引中
低效操作:
- 取反效率低(比如不等于,因為等于會命中索引,取反不會)
- $nin 總是進行全表掃描
- 一次查詢隻能使用一個索引,$or 除外,但 $or 使用多個索引查詢之後再将結果進行合并的效率并不高,是以不推薦使用(盡可能使用$in)
- 嵌套對象字段索引與基本字段的處理方式一緻
使用索引的場景:
- 集合較大
- 文檔較大
- 選擇性查詢
// 背景建立索引,如果使用工具線程,可能會阻塞查詢
db.people.createIndex({zipcode: 1}, {background: true})
索引基數:資料類型多,索引基數高,索引效率高,如果資料比如性别隻有男,女兩種資料,索引效率低