"在Go语言的`mongo-driver`库中,创建索引时可以使用多种类型。以下是一些常见的索引类型以及对应的示例:
1. **单字段索引**:
```go
err := collection.Indexes().CreateOne(
context.TODO(),
mongo.IndexModel{
Keys: bson.M{"name": 1}, // 1 表示升序索引
},
)
```
2. **复合索引**:
```go
err := collection.Indexes().CreateOne(
context.TODO(),
mongo.IndexModel{
Keys: bson.M{"name": 1, "age": -1}, // -1 表示降序索引
},
)
```
3. **多键索引**(用于数组字段):
```go
err := collection.Indexes().CreateOne(
context.TODO(),
mongo.IndexModel{
Keys: bson.M{"ingredients": 1},
},
)
```
4. **地理空间索引**:
```go
err := collection.Indexes().CreateOne(
context.TODO(),
mongo.IndexModel{
Keys: bson.M{"location": "2dsphere"},
},
)
```
5. **文本索引**:
```go
err := collection.Indexes().CreateOne(
context.TODO(),
mongo.IndexModel{
Keys: bson.M{"$**": "text"},
},
)
```
6. **哈希索引**(通常用于分片键):
```go
err := collection.Indexes().CreateOne(
context.TODO(),
mongo.IndexModel{
Keys: bson.M{"_id": "hashed"},
},
)
```
请注意,在实际使用中,`context.TODO()`应替换为适当的`context.Context`,以确保索引创建操作的上下文正确。同时,`collection`应该是`mongo.Collection`类型的实例,代表要创建索引的集合。以上示例中的`err`应进行错误检查以确保索引创建成功。"