| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103 | package moimport (	"context"	"time"	"go.mongodb.org/mongo-driver/bson"	"go.mongodb.org/mongo-driver/bson/primitive")type oid struct{}func (oid) Key() string {	return "_id"}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 any) 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) {	var idxList A	if err := UnmarshalCursor(cursor, &idxList); err != nil {		return nil, err	}	idxMap := make(map[string]bool)	for _, idx := range idxList {		arr, ok := idx.(D)		if !ok {			panic(arr)		}		var (			key string			val bool		)		for _, ele := range arr {			if ele.Key == "name" {				key = ele.Value.(string)			}			if ele.Key == "unique" {				val = ele.Value.(bool)			}		}		idxMap[key] = val	}	return idxMap, nil}func UnmarshalCursor(cursor *Cursor, v interface{}) error {	ctx, cancel := context.WithTimeout(context.Background(), DefaultTimout)	defer func() {		_ = cursor.Close(ctx)		cancel()	}()	return cursor.All(ctx, v)}
 |