| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980 | package moimport (	"context"	"time"	"go.mongodb.org/mongo-driver/bson"	"go.mongodb.org/mongo-driver/bson/primitive")type oid struct{}func (oid) New() ObjectID {	return primitive.NewObjectID()}func (oid) From(hex string) (ObjectID, error) {	id, err := primitive.ObjectIDFromHex(hex)	if err != nil {		return NilObjectID, err	}	if id.IsZero() {		return NilObjectID, ErrInvalidHex	}	return id, nil}func (o oid) IsValid(hex string) bool {	_, err := o.From(hex)	return err == nil}var (	ID = oid{} // ID 用于 ObjectID 的 API)// UnmarshalExtJSON 将 json 字符串解析为 bson 类型// data 为字符串字节, canonical 是否为严格类型, val 需要绑定的类型// 可参考 https://www.mongodb.com/docs/manual/reference/mongodb-extended-json/#examples// 与 json.Unmarshal 不同的是: 当 val 为 D / M 时, 会保留 key 的顺序. 但由于 Go 语言 for 循环 map 时会打乱顺序, 因此如果对 key 的顺序// 有要求时请使用 D 作为绑定类型// 用法参见 TestUnmarshalExtJSONfunc UnmarshalExtJSON(data []byte, canonical bool, val interface{}) error {	return bson.UnmarshalExtJSON(data, canonical, val)}func MarshalExtJSON(val any, canonical, escapeHTML bool) ([]byte, error) {	return bson.MarshalExtJSON(val, canonical, escapeHTML)}func NewDateTimeFromTime(t time.Time) DateTime {	return primitive.NewDateTimeFromTime(t)}func NewDecimal128(h, l uint64) Decimal128 {	return primitive.NewDecimal128(h, l)}// ResolveIndexName 从 cursor 中解析出索引名称, 索引名称见 IndexName// bool 表示 uniquefunc ResolveIndexName(cursor *Cursor) (map[string]bool, error) {	idxMap := make(map[string]bool)	ctx, cancel := context.WithTimeout(context.Background(), DefaultTimout)	defer func() {		_ = cursor.Close(ctx)		cancel()	}()	for cursor.Next(ctx) {		var now M		if err := cursor.Decode(&now); err != nil {			return nil, err		}		var unique bool		if v, ok := now["unique"].(bool); ok {			unique = v		}		idxMap[now["name"].(string)] = unique	}	return idxMap, nil}
 |