开发环境

  1. $ docker run -d --name mongo \
  2. -p 27017:27017 \
  3. -e MONGO_INITDB_ROOT_USERNAME=admin \
  4. -e MONGO_INITDB_ROOT_PASSWORD=654321 \
  5. mongo:4.0

go.mod 设置

  1. go 1.14
  2. require go.mongodb.org/mongo-driver v1.4.6

连接

  1. package main
  2. import (
  3. "context"
  4. "log"
  5. "time"
  6. "go.mongodb.org/mongo-driver/mongo"
  7. "go.mongodb.org/mongo-driver/mongo/options"
  8. "go.mongodb.org/mongo-driver/mongo/readpref"
  9. )
  10. func main() {
  11. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  12. defer cancel()
  13. client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost:27017"))
  14. err = client.Ping(ctx, readpref.Primary())
  15. if err != nil {
  16. log.Fatal(err)
  17. }
  18. log.Println("mongodb connect success")
  19. }

连接和集合

  1. // database
  2. database := client.Database("my_db")
  3. // collection
  4. collection := database.Collection("my_collection")
  5. log.Println(collection.Name())

插入一条数据

  1. package main
  2. import (
  3. "context"
  4. "log"
  5. "time"
  6. "go.mongodb.org/mongo-driver/bson/primitive"
  7. "go.mongodb.org/mongo-driver/mongo"
  8. "go.mongodb.org/mongo-driver/mongo/options"
  9. "go.mongodb.org/mongo-driver/mongo/readpref"
  10. )
  11. type Student struct {
  12. Name string `bson:"name"` // 名字
  13. Gender string `bson:gender` // 性别
  14. Age int8 `bson:"age"` // 年龄
  15. }
  16. func main() {
  17. clientOptions := options.Client().SetHosts([]string{"localhost:27017"}).
  18. SetConnectTimeout(5 * time.Second).
  19. SetAuth(options.Credential{Username: "admin", Password: "654321"})
  20. ctx := context.TODO()
  21. client, err := mongo.Connect(ctx, clientOptions)
  22. err = client.Ping(ctx, readpref.Primary())
  23. if err != nil {
  24. log.Fatal(err)
  25. }
  26. log.Println("mongodb connect success")
  27. // database
  28. database := client.Database("my_db")
  29. // collection
  30. collection := database.Collection("my_collection")
  31. s := &Student{
  32. Name: "张三",
  33. Gender: "男",
  34. Age: 20,
  35. }
  36. res, err := collection.InsertOne(context.TODO(), s)
  37. if err != nil {
  38. log.Fatal(err)
  39. }
  40. docId := res.InsertedID.(primitive.ObjectID)
  41. recordId := docId.Hex()
  42. log.Println("insert one ID str is :", recordId)
  43. }

插入多条数据

  1. package main
  2. import (
  3. "context"
  4. "log"
  5. "time"
  6. "go.mongodb.org/mongo-driver/mongo"
  7. "go.mongodb.org/mongo-driver/mongo/options"
  8. "go.mongodb.org/mongo-driver/mongo/readpref"
  9. )
  10. type Student struct {
  11. Name string `bson:"name"` // 名字
  12. Gender string `bson:gender` // 性别
  13. Age int8 `bson:"age"` // 年龄
  14. }
  15. func main() {
  16. clientOptions := options.Client().SetHosts([]string{"localhost:27017"}).
  17. SetConnectTimeout(5 * time.Second).
  18. SetAuth(options.Credential{Username: "admin", Password: "654321"})
  19. ctx := context.TODO()
  20. client, err := mongo.Connect(ctx, clientOptions)
  21. err = client.Ping(ctx, readpref.Primary())
  22. if err != nil {
  23. log.Fatal(err)
  24. }
  25. log.Println("mongodb connect success")
  26. collection := client.Database("my_db").Collection("my_collection")
  27. s1 := &Student{
  28. Name: "李四",
  29. Gender: "男",
  30. Age: 18,
  31. }
  32. s2 := &Student{
  33. Name: "王五",
  34. Gender: "女",
  35. Age: 30,
  36. }
  37. res, err := collection.InsertMany(context.TODO(), []interface{}{s1, s2})
  38. if err != nil {
  39. log.Fatal(err)
  40. }
  41. log.Println("insert manyID is :", res)
  42. }

查找单条数据

  1. package main
  2. import (
  3. "context"
  4. "go.mongodb.org/mongo-driver/bson"
  5. "log"
  6. "time"
  7. "go.mongodb.org/mongo-driver/mongo"
  8. "go.mongodb.org/mongo-driver/mongo/options"
  9. "go.mongodb.org/mongo-driver/mongo/readpref"
  10. )
  11. type Student struct {
  12. Name string `bson:"name"` // 名字
  13. Gender string `bson:gender` // 性别
  14. Age int8 `bson:"age"` // 年龄
  15. }
  16. func main() {
  17. clientOptions := options.Client().SetHosts([]string{"localhost:27017"}).
  18. SetConnectTimeout(5 * time.Second).
  19. SetAuth(options.Credential{Username: "admin", Password: "654321"})
  20. ctx := context.TODO()
  21. client, err := mongo.Connect(ctx, clientOptions)
  22. err = client.Ping(ctx, readpref.Primary())
  23. if err != nil {
  24. log.Fatal(err)
  25. }
  26. log.Println("mongodb connect success")
  27. collection := client.Database("my_db").Collection("my_collection")
  28. filter := bson.M{"name": "张三"}
  29. res := collection.FindOne(ctx, filter)
  30. if res == nil || res.Err() != nil {
  31. log.Fatal("find one error ", res.Err().Error())
  32. }
  33. var s Student
  34. err = res.Decode(&s)
  35. if err != nil {
  36. log.Fatal("find one failed error is ", err)
  37. }
  38. log.Println("find one success, res is ", s)
  39. }

查找多条

  1. package main
  2. import (
  3. "context"
  4. "log"
  5. "time"
  6. "go.mongodb.org/mongo-driver/bson"
  7. "go.mongodb.org/mongo-driver/mongo"
  8. "go.mongodb.org/mongo-driver/mongo/options"
  9. "go.mongodb.org/mongo-driver/mongo/readpref"
  10. )
  11. type Student struct {
  12. ID string `bson:"_id,omitempty"`
  13. Name string `bson:"name"` // 名字
  14. Gender string `bson:gender` // 性别
  15. Age int8 `bson:"age"` // 年龄
  16. }
  17. func main() {
  18. clientOptions := options.Client().SetHosts([]string{"localhost:27017"}).
  19. SetConnectTimeout(5 * time.Second).
  20. SetAuth(options.Credential{Username: "admin", Password: "654321"})
  21. ctx := context.TODO()
  22. client, err := mongo.Connect(ctx, clientOptions)
  23. err = client.Ping(ctx, readpref.Primary())
  24. if err != nil {
  25. log.Fatal(err)
  26. }
  27. log.Println("mongodb connect success")
  28. collection := client.Database("my_db").Collection("my_collection")
  29. filter := bson.M{"age": bson.M{"$gte": 20}}
  30. cursor, err := collection.Find(ctx, filter)
  31. if err != nil {
  32. log.Fatal("find error ", err)
  33. return
  34. }
  35. defer cursor.Close(context.Background())
  36. list := make([]Student, 0, cursor.RemainingBatchLength())
  37. for cursor.Next(context.Background()) {
  38. var s Student
  39. err := cursor.Decode(&s)
  40. if err != nil {
  41. log.Println("decode error is ", err)
  42. continue
  43. }
  44. list = append(list, s)
  45. }
  46. log.Println("find result ", list)
  47. }

分页查找

  1. package main
  2. import (
  3. "context"
  4. "log"
  5. "time"
  6. "go.mongodb.org/mongo-driver/bson"
  7. "go.mongodb.org/mongo-driver/mongo"
  8. "go.mongodb.org/mongo-driver/mongo/options"
  9. "go.mongodb.org/mongo-driver/mongo/readpref"
  10. )
  11. type Student struct {
  12. ID string `bson:"_id,omitempty"`
  13. Name string `bson:"name"` // 名字
  14. Gender string `bson:gender` // 性别
  15. Age int8 `bson:"age"` // 年龄
  16. }
  17. func main() {
  18. clientOptions := options.Client().SetHosts([]string{"localhost:27017"}).
  19. SetConnectTimeout(5 * time.Second).
  20. SetAuth(options.Credential{Username: "admin", Password: "654321"})
  21. ctx := context.TODO()
  22. client, err := mongo.Connect(ctx, clientOptions)
  23. err = client.Ping(ctx, readpref.Primary())
  24. if err != nil {
  25. log.Fatal(err)
  26. }
  27. log.Println("mongodb connect success")
  28. collection := client.Database("my_db").Collection("my_collection")
  29. filter := bson.M{"age": bson.M{"$gte": 0}}
  30. sort := bson.D{{"age", -1}}
  31. findOptions := options.Find().SetSort(sort)
  32. //从第1页获取,每次获取5条
  33. page := 1
  34. size := 5
  35. skipTmp := int64((page - 1) * size)
  36. limitTmp := int64(size)
  37. findOptions.Skip = &skipTmp
  38. findOptions.Limit = &limitTmp
  39. cursor, err := collection.Find(ctx, filter, findOptions)
  40. defer cursor.Close(context.Background())
  41. if err != nil {
  42. log.Fatal("limit page error is ", err)
  43. }
  44. for cursor.Next(context.Background()) {
  45. var s Student
  46. err := cursor.Decode(&s)
  47. if err != nil {
  48. log.Println("data decode error", err)
  49. continue
  50. }
  51. log.Println(s)
  52. }
  53. }

更新单条数据

  1. package main
  2. import (
  3. "context"
  4. "log"
  5. "time"
  6. "go.mongodb.org/mongo-driver/bson"
  7. "go.mongodb.org/mongo-driver/mongo"
  8. "go.mongodb.org/mongo-driver/mongo/options"
  9. "go.mongodb.org/mongo-driver/mongo/readpref"
  10. )
  11. type Student struct {
  12. ID string `bson:"_id,omitempty"`
  13. Name string `bson:"name"` // 名字
  14. Gender string `bson:gender` // 性别
  15. Age int8 `bson:"age"` // 年龄
  16. }
  17. func main() {
  18. clientOptions := options.Client().SetHosts([]string{"localhost:27017"}).
  19. SetConnectTimeout(5 * time.Second).
  20. SetAuth(options.Credential{Username: "admin", Password: "654321"})
  21. ctx := context.TODO()
  22. client, err := mongo.Connect(ctx, clientOptions)
  23. err = client.Ping(ctx, readpref.Primary())
  24. if err != nil {
  25. log.Fatal(err)
  26. }
  27. log.Println("mongodb connect success")
  28. collection := client.Database("my_db").Collection("my_collection")
  29. filter := bson.M{"name": "李四"}
  30. value := bson.M{"$set": bson.M{
  31. "age": 25}}
  32. res, err := collection.UpdateOne(ctx, filter, value)
  33. if err != nil {
  34. log.Println("update data err", err)
  35. return
  36. }
  37. log.Println("update count", res.ModifiedCount)
  38. }

修改多条数据

  1. package main
  2. import (
  3. "context"
  4. "log"
  5. "time"
  6. "go.mongodb.org/mongo-driver/bson"
  7. "go.mongodb.org/mongo-driver/mongo"
  8. "go.mongodb.org/mongo-driver/mongo/options"
  9. "go.mongodb.org/mongo-driver/mongo/readpref"
  10. )
  11. type Student struct {
  12. ID string `bson:"_id,omitempty"`
  13. Name string `bson:"name"` // 名字
  14. Gender string `bson:gender` // 性别
  15. Age int8 `bson:"age"` // 年龄
  16. }
  17. func main() {
  18. clientOptions := options.Client().SetHosts([]string{"localhost:27017"}).
  19. SetConnectTimeout(5 * time.Second).
  20. SetAuth(options.Credential{Username: "admin", Password: "654321"})
  21. ctx := context.TODO()
  22. client, err := mongo.Connect(ctx, clientOptions)
  23. err = client.Ping(ctx, readpref.Primary())
  24. if err != nil {
  25. log.Fatal(err)
  26. }
  27. log.Println("mongodb connect success")
  28. collection := client.Database("my_db").Collection("my_collection")
  29. var names = []string{"张三", "李四"}
  30. filter := bson.M{"name": bson.M{"$in": names}}
  31. value := bson.M{"$set": bson.M{"age": 22}}
  32. result, err := collection.UpdateMany(ctx, filter, value)
  33. if err != nil {
  34. log.Fatal("update many error", err)
  35. }
  36. log.Println("update count ", result.ModifiedCount)
  37. }

删除

  1. package main
  2. import (
  3. "context"
  4. "log"
  5. "time"
  6. "go.mongodb.org/mongo-driver/bson"
  7. "go.mongodb.org/mongo-driver/mongo"
  8. "go.mongodb.org/mongo-driver/mongo/options"
  9. "go.mongodb.org/mongo-driver/mongo/readpref"
  10. )
  11. type Student struct {
  12. ID string `bson:"_id,omitempty"`
  13. Name string `bson:"name"` // 名字
  14. Gender string `bson:gender` // 性别
  15. Age int8 `bson:"age"` // 年龄
  16. }
  17. func main() {
  18. clientOptions := options.Client().SetHosts([]string{"localhost:27017"}).
  19. SetConnectTimeout(5 * time.Second).
  20. SetAuth(options.Credential{Username: "admin", Password: "654321"})
  21. ctx := context.TODO()
  22. client, err := mongo.Connect(ctx, clientOptions)
  23. err = client.Ping(ctx, readpref.Primary())
  24. if err != nil {
  25. log.Fatal(err)
  26. }
  27. log.Println("mongodb connect success")
  28. collection := client.Database("my_db").Collection("my_collection")
  29. filter := bson.D{{"name", "张三"}}
  30. res, err := collection.DeleteOne(ctx, filter)
  31. if err != nil {
  32. log.Fatal(err)
  33. }
  34. log.Println("delete count", res.DeletedCount)
  35. }