赞
踩
目录
前言:本文主要演示了如何使用go语言操作mongodb,包括连接mongodb,操作数据等等。
- go get go.mongodb.org/mongo-driver/mongo
-
- go get go.mongodb.org/mongo-driver/mongo/options
- package mongodb
-
- import (
- "context"
- "fmt"
- "go.mongodb.org/mongo-driver/mongo"
- "go.mongodb.org/mongo-driver/mongo/options"
- "time"
- )
-
- var client *mongo.Client
- var coll *mongo.Collection
-
- func Init() (err error) {
- // 1.连接mongodb
- client, err = mongo.Connect(context.Background(),
- options.Client().ApplyURI("mongodb://localhost:27017").
- SetConnectTimeout(5*time.Second))
- if err != nil {
- fmt.Println(err)
- return err
- }
-
- if err = client.Ping(context.Background(), nil); err != nil {
- fmt.Println(err)
- return err
- }
-
- // 由于都是对同一个集合进行操作,所以在初始化mongodb时就选择了集合,防止后续出现大量重复代码
- coll = client.Database("db").Collection("stu")
- return
- }
-
- func GetClient() *mongo.Client {
- return client
- }
-
- func Close() {
- _ = client.Disconnect(context.Background())
- }
- package models
-
- type Student struct {
- ID int `bson:"_id"`
- Age int `bson:"age"`
- Name string `bson:"name"`
- Addr string `bson:"address"`
- }
- package mongodb
-
- import (
- "context"
- "fmt"
- "mongo/models"
- )
-
- func InsertStudent(p *models.Student) error {
- // 插入文档
- if _, err := coll.InsertOne(context.Background(), p); err != nil {
- return err
- }
- fmt.Println("Document inserted successfully!")
- return nil
- }
- package mongodb
-
- import (
- "context"
- "fmt"
- "mongo/models"
- )
-
-
- func InsertStudents(p []interface{}) error {
-
- // 插入多条文档
- if _, err := coll.InsertMany(context.Background(), p); err != nil {
- return err
- }
- fmt.Println("Document inserted successfully!")
- return nil
- }
- package main
-
- import (
- "fmt"
- "mongo/models"
- "mongo/mongodb"
- )
-
- func main() {
- // 1.连接mongodb
- if err := mongodb.Init(); err != nil {
- return
- }
- defer mongodb.Close()
-
- stus := []interface{}{
- models.Student{
- ID: 1,
- Age: 18,
- Name: "alice",
- Addr: "beijing",
- },
- models.Student{
- ID: 2,
- Age: 19,
- Name: "bob",
- Addr: "shanghai",
- },
- models.Student{
- ID: 3,
- Age: 20,
- Name: "charlie",
- Addr: "guangzhou",
- },
- }
- if err := mongodb.InsertStudents(stus); err != nil {
- return
- }
- }
- package mongodb
-
- import (
- "context"
- "fmt"
- "go.mongodb.org/mongo-driver/bson"
- )
-
- func DeleteStudent(p int) error {
-
- // 过滤条件
- fil := bson.M{"_id": p}
-
- // 删除文档
- if _, err := coll.DeleteOne(context.Background(), fil); err != nil {
- return err
- }
- fmt.Println("Document Delete successfully!")
- return nil
- }
- package mongodb
-
- import (
- "context"
- "fmt"
- "go.mongodb.org/mongo-driver/bson"
- "mongo/models"
- )
-
- // UpdateStudent 根据传入的参数进行更新
- func UpdateStudent(p *models.Student) error {
-
- // 根据条件筛选要更新的文档
- filter := bson.M{"_id": p.ID}
- update := bson.M{"$set": p}
-
- // 更新文档
- if _, err := coll.UpdateOne(context.Background(), filter, update); err != nil {
- return err
- }
- fmt.Println("Document Update successfully!")
- return nil
- }
-
- // UpdateStudents 修改所有符合条件的数据update stu set age = 99 where name = ?
- func UpdateStudents(p string) error {
-
- // 根据条件筛选要更新的文档
- filter := bson.M{"name": p}
- update := bson.M{"$set": bson.M{"age": 99}}
-
- // 更新文档
- if _, err := coll.UpdateMany(context.Background(), filter, update); err != nil {
- return err
- }
- fmt.Println("Document Update successfully!")
- return nil
- }
- package mongodb
-
- import (
- "context"
- "fmt"
- "go.mongodb.org/mongo-driver/bson"
- "go.mongodb.org/mongo-driver/mongo/options"
- "mongo/models"
- )
-
- // QueryStudentByID select * from stu where id = ?
- func QueryStudentByID(p int) error {
- filter := bson.M{"_id": p} // 根据条件筛选要更新的文档
-
- var s models.Student
- // 插入文档
- err := coll.FindOne(context.Background(), filter).Decode(&s)
- if err != nil {
- return err
- }
-
- fmt.Println("Document Find successfully!")
- fmt.Printf("Document Find: %+v", s)
-
- return nil
- }
- // QueryStudentByID1 投影查询,类似select name age from stu where id = ?
- func QueryStudentByID1(p int) error {
- filter := bson.M{"_id": p} // 根据条件筛选要更新的文档
-
- // 投影选项
- d := bson.D{
- {"name", 1},
- {"age", 1},
- }
-
- // 查询文档
- res, err := coll.Find(context.Background(), filter, options.Find().SetProjection(d))
- if err != nil {
- return err
- }
- fmt.Println("Document Find successfully!")
- defer res.Close(context.Background())
-
- var stus []models.Student
- if err = res.All(context.Background(), &stus); err != nil {
- return err
- }
- for _, s := range stus {
- fmt.Printf("Document found: %+v\n", s)
- }
-
- return nil
- }
- // QueryStudent 分页查询 select * from stu limit ?
- func QueryStudent(size int64) error {
-
- // 分页选项
- l := options.Find().SetLimit(size)
- filter := bson.M{}
- // 插入文档
- res, err := coll.Find(context.TODO(), filter, l)
- if err != nil {
- return err
- }
-
- fmt.Println("Document Find successfully!")
- defer res.Close(context.Background())
-
- var stus []models.Student
- if err = res.All(context.Background(), &stus); err != nil {
- return err
- }
- for _, s := range stus {
- fmt.Printf("Document found: %+v\n", s)
- }
-
- return nil
- }
- // QueryStudentByID3 跳过指定数量的数据
- func QueryStudentByID3(p int64) error {
- // 跳跃选项
- l := options.Find().SetSkip(p)
- filter := bson.M{}
-
- // 插入文档
- res, err := coll.Find(context.TODO(), filter, l)
- if err != nil {
- return err
- }
-
- fmt.Println("Document Find successfully!")
- defer res.Close(context.Background())
-
- var stus []models.Student
- if err = res.All(context.Background(), &stus); err != nil {
- return err
- }
-
- for _, s := range stus {
- fmt.Printf("Document found: %+v\n", s)
- }
-
- return nil
- }
- // QueryStudent2 对查询结果进行降序排序,入参为1升序,入参-1降序
- func QueryStudent2(p int) error {
- // select * from stu order by age desc
- // 排序选项
- s := options.Find().SetSort(bson.D{{"age", p}})
- filter := bson.M{}
-
- // 3.插入文档
- res, err := coll.Find(context.TODO(), filter, s)
- if err != nil {
- return err
- }
-
- fmt.Println("Document Find successfully!")
- defer res.Close(context.Background())
-
- var stus []models.Student
- if err = res.All(context.Background(), &stus); err != nil {
- return err
- }
- for _, s := range stus {
- fmt.Printf("Document found: %+v\n", s)
- }
-
- return nil
- }
- // QueryStudent3 模糊查询 select * from stu where name like %?%
- func QueryStudent3(p string) error {
- filter := bson.M{
- "name": bson.M{
- "$regex": p,
- },
- }
-
- //filter1 := bson.M{
- // "name": bson.M{
- // "$regex": fmt.Sprintf("^%s", p), //name like ?%
- // },
- //}
-
- // 查询
- res, err := coll.Find(context.TODO(), filter)
- if err != nil {
- return err
- }
-
- fmt.Println("Document Find successfully!")
- defer res.Close(context.Background())
-
- var stus []models.Student
- if err = res.All(context.Background(), &stus); err != nil {
- return err
- }
-
- for _, s := range stus {
- fmt.Printf("Document found: %+v\n", s)
- }
- return nil
- }
- // QueryStudent4 比较查询 select * from stu where age > ?
- func QueryStudent4(p int) error {
- // 过滤条件
- filter := bson.M{
- "age": bson.M{
- "$gt": p, // age > p
- // $lt <
- // $gte >=
- // $lte <=
- // $ne !=
- },
- }
-
- // 查询
- res, err := coll.Find(context.TODO(), filter)
- if err != nil {
- return err
- }
-
- fmt.Println("Document Find successfully!")
- defer res.Close(context.Background())
-
- var stus []models.Student
- if err = res.All(context.Background(), &stus); err != nil {
- return err
- }
-
- for _, s := range stus {
- fmt.Printf("Document found: %+v\n", s)
- }
- return nil
- }
-
- // QueryStudent5 包含查询 select * from stu where age in [s, e]
- func QueryStudent5(s, e int) error {
- // 过滤条件
- filter := bson.M{
- "age": bson.M{
- "$in": []int{s, e}, // age in [s, e]
- // "$nin": []int{s, e}, // age not in [s, e]
- },
- }
-
- // 查询
- res, err := coll.Find(context.TODO(), filter)
- if err != nil {
- return err
- }
-
- fmt.Println("Document Find successfully!")
- defer res.Close(context.Background())
-
- var stus []models.Student
- if err = res.All(context.Background(), &stus); err != nil {
- return err
- }
-
- for _, s := range stus {
- fmt.Printf("Document found: %+v\n", s)
- }
- return nil
- }
- // QueryStudent6 连接查询 select * from stu where age = ? and name = ?
- func QueryStudent6(age int, name string) error {
- // 过滤条件
- filter := bson.M{
-
- // age = ? and name = ?
- "$and": []bson.M{
- {"age": age},
- {"name": name},
- },
-
- // age > ? and name = ?
- //"$and": []bson.M{
- // bson.M{"age": bson.M{"$gt": 20}},
- // bson.M{"name": "zhaoliu"},
- //},
-
- // age > ? or name = ?
- //"$or": []bson.M{
- // bson.M{"age": bson.M{"$gt": 20}},
- // bson.M{"name": "zhaoliu"},
- //},
- }
-
- // 查询
- res, err := coll.Find(context.TODO(), filter)
- if err != nil {
- return err
- }
-
- fmt.Println("Document Find successfully!")
- defer res.Close(context.Background())
-
- var stus []models.Student
- if err = res.All(context.Background(), &stus); err != nil {
- return err
- }
-
- for _, s := range stus {
- fmt.Printf("Document found: %+v\n", s)
- }
- return nil
- }
以上就是今天要讲的内容,如何使用go语言操作mongodb,展示了mongodb的部分指令,而mongodb提供的指令远不止这些,在学习的过程中做笔记,以防日后需要使用mongodb会忘记怎么使用,毕竟好记性不如烂笔头。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。