Package mongo 为 Go 提供了一个 MongoDB Driver API。

import “go.mongodb.org/mongo-driver/mongo” import “go.mongodb.org/mongo-driver/mongo/options”

image.png

1 代码示例

  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "go.mongodb.org/mongo-driver/bson"
  6. "go.mongodb.org/mongo-driver/mongo"
  7. "go.mongodb.org/mongo-driver/mongo/options"
  8. )
  9. type User struct {
  10. Name string `bson:"name"`
  11. Age int `bson:"age"`
  12. BirthMonth int `bson:"birth_month"`
  13. gender string `bson:"gender"`
  14. }
  15. // 新建MongoDB客户端对象
  16. func NewMongoClient() *mongo.Client {
  17. clientOptions := options.Client().ApplyURI("mongodb://127.0.0.1:27017")
  18. var err error
  19. client, err := mongo.Connect(context.TODO(), clientOptions)
  20. if err != nil {
  21. fmt.Println(err)
  22. return nil
  23. }
  24. // 检查是否连接正常
  25. err = client.Ping(context.TODO(), nil)
  26. if err != nil {
  27. fmt.Println(err)
  28. return nil
  29. }
  30. return client
  31. }
  32. // 单条插入
  33. func insertOne(c *mongo.Collection) {
  34. res, _ := c.InsertOne(context.Background(), bson.M{"name": "ws1", "age": 19})
  35. id := res.InsertedID
  36. fmt.Println(id)
  37. res, _ = c.InsertOne(context.Background(), bson.M{"name": "ws2", "age": 18})
  38. id = res.InsertedID
  39. fmt.Println(id)
  40. }
  41. // 多条插入
  42. func insertMany(c *mongo.Collection) {
  43. c.InsertMany(context.Background(), []interface{}{
  44. bson.M{"name": "ws3", "age": 19},
  45. bson.M{"name": "ws4", "age": 18},
  46. bson.M{"name": "ws5", "age": 17},
  47. bson.M{"name": "ws6", "age": 18},
  48. })
  49. }
  50. // 查找单条
  51. func findOne(c *mongo.Collection) {
  52. singleResult := c.FindOne(context.Background(), bson.M{
  53. "name": "ws1",
  54. })
  55. if singleResult == nil || singleResult.Err() != nil {
  56. return
  57. }
  58. userData := User{}
  59. err := singleResult.Decode(&userData)
  60. if err != nil {
  61. return
  62. }
  63. fmt.Println(userData)
  64. }
  65. // 查找多条
  66. func findMany(c *mongo.Collection) {
  67. cursor, err := c.Find(context.Background(), bson.M{
  68. "age": bson.M{"$lte": 18},
  69. })
  70. if err != nil {
  71. return
  72. }
  73. for cursor.Next(context.Background()) {
  74. userData := User{}
  75. err := cursor.Decode(&userData)
  76. if err != nil {
  77. continue
  78. }
  79. fmt.Println(userData)
  80. }
  81. }
  82. // 更新一条
  83. func updateOne(c *mongo.Collection) {
  84. filter := bson.M{"name": "ws1"}
  85. value := bson.M{"$set": bson.M{"age": 100}}
  86. c.UpdateOne(context.Background(), filter, value)
  87. }
  88. // 更新多条
  89. func updateMany(c *mongo.Collection) {
  90. filter := bson.M{"age": 18}
  91. value := bson.M{"$set": bson.M{"age": 22}}
  92. c.UpdateMany(context.Background(), filter, value)
  93. }
  94. // 分组查询
  95. func findGroup(c *mongo.Collection) {
  96. // 复杂查询, 先匹配后分组
  97. filter := bson.A{ // A表示Array
  98. bson.M{
  99. "$group": bson.M{
  100. "_id": "$gender", // 按性别分组
  101. "minAge": bson.M{"$min": "$age"},
  102. "maxBirthMonth": bson.M{"$max": "$birth_month"},
  103. },
  104. },
  105. }
  106. cursor, err := c.Aggregate(context.Background(), filter)
  107. if err != nil {
  108. fmt.Println(err)
  109. return
  110. }
  111. for cursor.Next(context.Background()) {
  112. doc := cursor.Current
  113. // LookupErr取出key里的值
  114. minAge, err2 := doc.LookupErr("minAge")
  115. if err2 != nil {
  116. return
  117. }
  118. fmt.Println(minAge) // {"$numberInt":"19"}
  119. maxBirthMonth, err3 := doc.LookupErr("maxBirthMonth")
  120. if err3 != nil {
  121. return
  122. }
  123. fmt.Println(maxBirthMonth) // {"$numberDouble":"4.0"}
  124. }
  125. }
  126. // 分页查询
  127. func findPage(c *mongo.Collection) {
  128. filter := bson.M{"age": bson.M{"$lt": 50}}
  129. cursor, err := c.Find(context.Background(), filter,
  130. options.Find().SetSort(bson.D{{"age", -1}}),
  131. options.Find().SetLimit(4),
  132. options.Find().SetSkip(1))
  133. if err != nil {
  134. return
  135. }
  136. var users []User
  137. err2 := cursor.All(context.Background(), &users)
  138. if err2 != nil {
  139. return
  140. }
  141. for _, user := range users {
  142. fmt.Println(user.Name, user.Age)
  143. }
  144. }
  145. func main() {
  146. // 创建客户端对象
  147. client := NewMongoClient()
  148. // 创建集合对象
  149. c := client.Database("wstest").Collection("users")
  150. // 执行代码
  151. findPage(c)
  152. }

2 json字符串 转 bson

  1. package main
  2. import (
  3. "fmt"
  4. "go.mongodb.org/mongo-driver/bson"
  5. )
  6. func main() {
  7. var json = "{\"data\":1}"
  8. var workflow interface{}
  9. e := bson.UnmarshalExtJSON([]byte(json), false, &workflow)
  10. if e != nil {
  11. fmt.Println("err is ", e)
  12. return
  13. }
  14. fmt.Println(workflow)
  15. }