| 1234567891011121314151617181920212223242526272829303132333435363738394041424344 | 
							- package mo
 
- import (
 
- 	"fmt"
 
- 	"go.mongodb.org/mongo-driver/mongo/options"
 
- )
 
- // NewIndexModel 创建索引
 
- // 参考 https://www.mongodb.com/docs/manual/core/index-single/
 
- //
 
- //	https://www.mongodb.com/docs/manual/indexes/
 
- //
 
- // field 为需要创建索引的字段, 而 i 为 1 或 -1 用于索引的字段排序, 即最终的索引名称为 field + 下划线 + i
 
- // 例如: field_1
 
- // 索引的顺序无关紧要, 参见 https://www.mongodb.com/docs/manual/indexes/#single-field
 
- // 为了方便操作, mo 永远将 i 设置为 1
 
- // 通常情况下应使用 NewIndex 创建索引
 
- func NewIndexModel(filed string, i int32, unique bool) IndexModel {
 
- 	return IndexModel{
 
- 		Keys:    M{filed: i},
 
- 		Options: options.Index().SetUnique(unique), // 设置为唯一值
 
- 	}
 
- }
 
- // NewIndex 创建索引
 
- func NewIndex(field string, unique bool) IndexModel {
 
- 	return NewIndexModel(field, 1, unique)
 
- }
 
- // NewIndexes 批量创建索引
 
- func NewIndexes(field []string, unique bool) []IndexModel {
 
- 	index := make([]IndexModel, len(field))
 
- 	for i := 0; i < len(field); i++ {
 
- 		index[i] = NewIndex(field[i], unique)
 
- 	}
 
- 	return index
 
- }
 
- // IndexName 索引名称, 将 field 包装为 MongoDB 索引名称
 
- // 详情参见 NewIndexModel
 
- func IndexName(field string) string {
 
- 	return fmt.Sprintf("%s_1", field)
 
- }
 
 
  |