go insert mongo find mongo

 

 

 

func (conno *ConnoInfo) InsertConno() (interface{}, error) {

    ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
    collection_ex := beego.AppConfig.String("mongodb::mongodb_collection_ex")

    conno.ID = primitive.NewObjectID()
    //primitive.NewDateTimeFromTime(time.Now())

    conno.Ts = date_utils.JsonTime(time.Now())

    result, err := mongodb.Conn().Collection(fmt.Sprintf("%s%s", strings.ToLower(collection_ex), strings.ToLower(conno.Carriercd))).InsertOne(ctx, conno)

    objectID := result.InsertedID.(primitive.ObjectID)

    if err != nil {
        return nil, err
    }

    return objectID.Hex(), nil

}

 

 

 

 

common.go

package date_utils

import (
    "errors"
    "fmt"
    "go.mongodb.org/mongo-driver/bson"
    "go.mongodb.org/mongo-driver/bson/bsontype"
    "go.mongodb.org/mongo-driver/bson/primitive"
    "go.mongodb.org/mongo-driver/x/bsonx/bsoncore"
    "time"
)

type JsonTime time.Time

const (
    timeFormart = "2006-01-02 15:04:05"
)

func Now() JsonTime {
    return JsonTime(time.Now())
}

//实现json反序列化,从传递的字符串中解析成时间对象
func (t *JsonTime) UnmarshalJSON(data []byte) (err error) {

    if string(data) == "null" {
        return nil
    }

    now, err := time.ParseInLocation(`"`+timeFormart+`"`, string(data), time.Local)
    *t = JsonTime(now)
    return
}

//实现json序列化,将时间转换成字符串byte数组
func (t JsonTime) MarshalJSON() ([]byte, error) {
    b := make([]byte, 0, len(timeFormart)+2)
    b = append(b, '"')
    b = time.Time(t).AppendFormat(b, timeFormart)
    b = append(b, '"')
    return b, nil
}

//mongodb是存储bson格式,因此需要实现序列化bsonvalue(这里不能实现MarshalBSON,MarshalBSON是处理Document的),将时间转换成mongodb能识别的primitive.DateTime
func (t *JsonTime) MarshalBSONValue() (bsontype.Type, []byte, error) {
    targetTime := primitive.NewDateTimeFromTime(time.Time(*t))
    return bson.MarshalValue(targetTime)
}

//实现bson反序列化,从mongodb中读取数据转换成time.Time格式,这里用到了bsoncore中的方法读取数据转换成datetime然后再转换成time.Time
func (t *JsonTime) UnmarshalBSONValue(t2 bsontype.Type, data []byte) error {
    v, _, valid := bsoncore.ReadValue(data, t2)
    if valid == false {
        return errors.New(fmt.Sprintf("%s, %s, %s", "读取数据失败:", t2, data))
    }
    *t = JsonTime(v.Time())
    return nil
}

 

 

 

func (conno *ConnoInfo) GetConno(scac string) interface{} {

    ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
    //err := mongodb.Conn().FindOne(ctx, ConnoInfo{ID: conno.ID}).Decode(&conno)
    filter := bson.D{{"_id", conno.ID}}
    collection_ex := beego.AppConfig.String("mongodb::mongodb_collection_ex")

    err := mongodb.Conn().Collection(fmt.Sprintf("%s%s", strings.ToLower(collection_ex), strings.ToLower(scac))).FindOne(ctx, filter).Decode(&conno)

    if err != nil {
        //return errors.NewInternalServerError(err.Error())
        if ins := strings.Index(err.Error(), "no document"); ins > -1 {
            return utils.Response{201, "nodata", err.Error()}
        }
        return utils.Response{500, "error", err.Error()}
    }

    return nil
}

 

 

 

type ConnoInfo struct {

ID        primitive.ObjectID `json:"id" bson:"_id"`
Ts                date_utils.JsonTime `json:"ts" bson:"ts"`

}

 

posted @ 2022-04-26 11:16  AngDH  阅读(58)  评论(0编辑  收藏  举报