go操作mongo CRUD

最近的微服务用到了mongodb,所以先了解go对于mongoCRUD

查找

import "go.mongodb.org/mongo-driver/mongo"

// 通过用户id查找
func (this *User) FindOneById(user_id int64) (*User, error) {
    err := this.db.FindOne(nil, bson.D{{"id", user_id}}).Decode(this)
    return this, err
}

// 多个条件, `$or`累死与`mysql or`,
func (this *User) FindOneByNameOrPhone(name string, phone string) (*User, error) {
    conditions := bson.M{
        "$or": []bson.M{
            bson.M{"name": bson.M{"$eq": name}},
            bson.M{"phone": bson.M{"$eq": phone}},
        },
    }
    err := this.db.FindOne(context.TODO(), conditions).Decode(this)
    return this, err
}

插入

type User struct {
    Id         int64  `bson:"id"`
    Name       string `bson:"name"`
    NickName   string `bson:"nickname"`
    Password   string `bson:"password"`
    Phone      string `bson:"phone"`
    Email      string `bson:"email"`
    CreateTime int64  `bson:"create_time"`
    UpdateTime int64  `bson:"update_time"`
    db         *mongo.Collection
}

// 对结构体赋值后新增
func (this *User) Insert() (*mongo.InsertOneResult, error) {
    return this.db.InsertOne(context.TODO(), this)
}

// 插入多行记录
func (this *ActiveCode) InsertMany(acs []interface{}) (*mongo.InsertManyResult, error) {
  return this.db.InsertMany(context.Background(), acs)
}

// 调用model方法
codes := []string{"a","b","c"}
acModel := model.NewActiveCode()
var data  []interface{}
for _, i := range codes {
  if i == "" {
      continue
  }
 data = append(data,bson.D{
      {"user_id", 0},
      {"code", i},
      {"status", 0},
      {"data", ""},
      {"create_time", time.Now().Unix()},
      {"update_time", time.Now().Unix()},
  })
}
result, err := acModel.InsertMany(data)

更新

// 根据用户id更新数据,`$set` 类似 `mysql = `
func (this *User) UpdateById(userId int64, phone, email,nickName string) (interface{}, error) {
    // 条件
    filter := bson.D{{"id", userId}}
    // 更新
    update := bson.D{
        {
            "$set", bson.D{{"phone", phone}},
        },
        {
            "$set", bson.D{{"email", email}},
        },
        {
            "$set", bson.D{{"nickname", nickName}},
        },

    }
    // 更新操作
    result, err := this.db.UpdateOne(context.TODO(), filter, update)
    if err != nil {
        return nil, err
    }
    return result.UpsertedID, nil
}

删除

// 根据用户id删除
func (this *User) deleteById(userId int64) error {
    // 条件
    filter := bson.D{{"id", userId}}

    // 更新操作
    _, err := this.db.DeleteOne(context.TODO(), filter)
    if err != nil {
        return err
    }
    return nil
}
本作品采用《CC 协议》,转载必须注明作者和本文链接
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!
未填写
文章
39
粉丝
9
喜欢
71
收藏
102
排名:461
访问:1.9 万
私信
所有博文
社区赞助商