go语言 MongoDB CRDU操作

数据库驱动

go语言中mongodb 有一个社区驱动 mgo
mgo文档

但是最近mongo官方推出了Go驱动,所以我们用官方的。
相关链接 :
MongoDB 文档
MongoDB Go Driver

链接数据库

package db

var (
    dataBase *mongo.Database   //DB实例
    ctx context.Context  //DB context
    client   mongo.Client 
)

func init(){
    client, err := mongo.NewClient(options.Client().ApplyURI("mongodb://localhost:27017"))
    ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
    err = client.Connect(Ctx)
    if err != nil {
        log.Fatal(err.Error())
    }
    dataBase = client.Database(DATABASE_NAME)  //DATABASE_NAME即数据库名称
}
//在这下面定义两个函数来获取DB 和 context
func GetDB() *mongo.Database {
    return dataBase
}
func GetCtx() *context.Context{
      return ctx
}

数据库结构

假设有数据库结构如下:
Collection "user"
username string
password string
age int
created date
对应go的model如下:

package userModel
type User struct{
     Username string `bson:"username"`
     Password string `bson:"passowrd"`
     Age  int `bson:"age"`
     Created time.Time `bson:"created"`
}

插入操作

func AddOneUser () error{
      //获取collection
      con := db.GetDB().Collection("user")
      // 插入的数据     
      insertData := userModel.User{  
              Username:"123",
              Password:"321",
              Age : 18,
              Created:Time.Now(),
      }
      //下面的方法也可以  
      /*
      insertData := bson.M{
          Username:"123",
          Password:"321",
          Age : 18,
          Created:Time.Now(),
      }
      */
      //插入   
      result, err := con.InsertOne(db.GetCtx(), &insertData)
      log.PrintLn(result) //result 是插入后的结果,/插入/匹配/修改/删除/Upsert/  的document数量
      return err
} 

批量插入操作

func AddOneUser (users *[]User) error{
      //获取collection
      con := db.GetDB().Collection("user")
      // users 即插入的数据
      //插入   
      result, err := con.InsertMany(db.GetCtx(), users)
      log.PrintLn(result) //result 是插入后的结果,/插入/匹配/修改/删除/Upsert/  的document数量
      return err
} 

删除操作

func DeleteUser (name string) error{
      //通过name来删除user
      //获取collection
      con := db.GetDB().Collection("user")
      result, err := con.DeleteOne(db.GetCtx(),bson.M{"name":name})
      log.PrintLn(result) 
      return err
}

修改操作

func UpdateUser(name string,newUserInfo User) error{
      //通过name来更新  ,newUserInfo 是需要更新的user信息
      //获取collection
      con := db.GetDB().Collection("user")
      //匹配名称为name的文档记录  并更新为 newUserInfo 
      result, err := con.UpdateOne(db.GetCtx(), bson.M{"name":name},bson.M{"$set":newUserInfo})
      log.PrintLn(result) 
      return err
}

查询操作

func FindUserByName(name string) error{
      //通过name寻找user信息
      //获取collection
      con := db.GetDB().Collection("user")
      //将获取到的user储存在user变量中  
      user := User{}
      //查询到结果后解码到user变量中
       err := con.FindOne(db.GetCtx(), bson.M{"name":name}).Decode(&user)
     
      return err
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容