Package mongo 为 Go 提供了一个 MongoDB Driver API。
import “go.mongodb.org/mongo-driver/mongo” import “go.mongodb.org/mongo-driver/mongo/options”
1 代码示例
package mainimport ("context""fmt""go.mongodb.org/mongo-driver/bson""go.mongodb.org/mongo-driver/mongo""go.mongodb.org/mongo-driver/mongo/options")type User struct {Name string `bson:"name"`Age int `bson:"age"`BirthMonth int `bson:"birth_month"`gender string `bson:"gender"`}// 新建MongoDB客户端对象func NewMongoClient() *mongo.Client {clientOptions := options.Client().ApplyURI("mongodb://127.0.0.1:27017")var err errorclient, err := mongo.Connect(context.TODO(), clientOptions)if err != nil {fmt.Println(err)return nil}// 检查是否连接正常err = client.Ping(context.TODO(), nil)if err != nil {fmt.Println(err)return nil}return client}// 单条插入func insertOne(c *mongo.Collection) {res, _ := c.InsertOne(context.Background(), bson.M{"name": "ws1", "age": 19})id := res.InsertedIDfmt.Println(id)res, _ = c.InsertOne(context.Background(), bson.M{"name": "ws2", "age": 18})id = res.InsertedIDfmt.Println(id)}// 多条插入func insertMany(c *mongo.Collection) {c.InsertMany(context.Background(), []interface{}{bson.M{"name": "ws3", "age": 19},bson.M{"name": "ws4", "age": 18},bson.M{"name": "ws5", "age": 17},bson.M{"name": "ws6", "age": 18},})}// 查找单条func findOne(c *mongo.Collection) {singleResult := c.FindOne(context.Background(), bson.M{"name": "ws1",})if singleResult == nil || singleResult.Err() != nil {return}userData := User{}err := singleResult.Decode(&userData)if err != nil {return}fmt.Println(userData)}// 查找多条func findMany(c *mongo.Collection) {cursor, err := c.Find(context.Background(), bson.M{"age": bson.M{"$lte": 18},})if err != nil {return}for cursor.Next(context.Background()) {userData := User{}err := cursor.Decode(&userData)if err != nil {continue}fmt.Println(userData)}}// 更新一条func updateOne(c *mongo.Collection) {filter := bson.M{"name": "ws1"}value := bson.M{"$set": bson.M{"age": 100}}c.UpdateOne(context.Background(), filter, value)}// 更新多条func updateMany(c *mongo.Collection) {filter := bson.M{"age": 18}value := bson.M{"$set": bson.M{"age": 22}}c.UpdateMany(context.Background(), filter, value)}// 分组查询func findGroup(c *mongo.Collection) {// 复杂查询, 先匹配后分组filter := bson.A{ // A表示Arraybson.M{"$group": bson.M{"_id": "$gender", // 按性别分组"minAge": bson.M{"$min": "$age"},"maxBirthMonth": bson.M{"$max": "$birth_month"},},},}cursor, err := c.Aggregate(context.Background(), filter)if err != nil {fmt.Println(err)return}for cursor.Next(context.Background()) {doc := cursor.Current// LookupErr取出key里的值minAge, err2 := doc.LookupErr("minAge")if err2 != nil {return}fmt.Println(minAge) // {"$numberInt":"19"}maxBirthMonth, err3 := doc.LookupErr("maxBirthMonth")if err3 != nil {return}fmt.Println(maxBirthMonth) // {"$numberDouble":"4.0"}}}// 分页查询func findPage(c *mongo.Collection) {filter := bson.M{"age": bson.M{"$lt": 50}}cursor, err := c.Find(context.Background(), filter,options.Find().SetSort(bson.D{{"age", -1}}),options.Find().SetLimit(4),options.Find().SetSkip(1))if err != nil {return}var users []Usererr2 := cursor.All(context.Background(), &users)if err2 != nil {return}for _, user := range users {fmt.Println(user.Name, user.Age)}}func main() {// 创建客户端对象client := NewMongoClient()// 创建集合对象c := client.Database("wstest").Collection("users")// 执行代码findPage(c)}
2 json字符串 转 bson
package mainimport ("fmt""go.mongodb.org/mongo-driver/bson")func main() {var json = "{\"data\":1}"var workflow interface{}e := bson.UnmarshalExtJSON([]byte(json), false, &workflow)if e != nil {fmt.Println("err is ", e)return}fmt.Println(workflow)}
