[TOC] > [github.com](https://github.com/mongodb/mongo-go-driver) ## 连接 ``` xxx.db('mongodb://[yourname: your_pwd@]ip:27017[/Article]'); ``` ## 结构类型 ## 连接 ``` client, err := mongo.NewClient(options.Client().ApplyURI("mongodb://root:123456@localhost:27017")) client, err := mongo.NewClient(options.Client().ApplyURI("mongodb://root:123456@localhost:27017")) if err != nil { panic(client) } ctx, _ := context.WithTimeout(context.Background(), 10*time.Second) err = client.Connect(ctx) if err != nil { panic(err) } err = client.Ping(ctx, readpref.Primary()) if err != nil { panic(err) } //连接库名,连接集合名 collection := client.Database("demo").Collection("numbers") ``` ## 插入 ### 插入单挑条 ``` //连接库名,连接集合名 collection := client.Database("demo").Collection("numbers") //mongodb能识别出类型 result, err := collection.InsertOne(ctx, bson.M{"name": "cc", "age": 123}) if err != nil { log.Printf("%v",err) } fmt.Printf("%+v\n", result.InsertedID) // ObjectID("5e0d65d4410d8db85702208c") ``` ### 插入多条 ``` var docs []interface{} docs = append(docs, bson.M{"name":"cpj","age":1}) docs = append(docs, bson.M{"name":"cpj2","age":2}) //mongodb能识别出类型 result, err := collection.InsertMany(ctx, docs) if err != nil { log.Printf("%v", err) } fmt.Printf("%+v\n", result.InsertedIDs) // [ObjectID("5e0d6784c70cf1dc87aaa8dc") ObjectID("5e0d6784c70cf1dc87aaa8dd")] ``` ## 查询 ## 单结果查询 ``` filter := bson.M{"name": "cc"} var result bson.M err = collection.FindOne(ctx, filter).Decode(&result) if err != nil { log.Printf("%v",err) } fmt.Printf("%+v\n", result) //map[_id:ObjectID("5e0d64422f5816e60c2df86a") age:1 name:cc] ``` ### 多结果条件查询 ``` filter := bson.M{"name": "cc"} sort := bson.D{{"age", 1}} opts := options.Find(). SetLimit(2). SetSort(sort) cur, err := collection.Find(ctx, filter,opts) if err != nil { log.Fatal(err) } defer cur.Close(ctx) var results []bson.M err = cur.All(ctx, &results) if err != nil { log.Printf("%v",err) } fmt.Printf("%+v\n", results) //[map[_id:ObjectID("5e0d64422f5816e60c2df86a") age:1 name:cc] map[_id:ObjectID("5e0d65d4410d8db85702208b") age:3 name:cc]] ``` ## 文件上传下载 ``` //指定数据库 databases := client.Database("gridfs") bucket, err := gridfs.NewBucket(databases) filename := "go.mod1" if err != nil { log.Printf("%v", err) } //文件上传 fileData, _ := ioutil.ReadFile(filename) ids, err := bucket.UploadFromStream(filename, bytes.NewReader(fileData)) //此处 filename 是 数据库显示的文件名 if err != nil { log.Printf("%v", err) } fmt.Printf("%+v\n", ids) //文件下载 var byt bytes.Buffer n, err := bucket.DownloadToStreamByName(filename, &byt) if err != nil { log.Printf("%v",err) } fmt.Printf("File size to download: %v 字节\n", n) err = ioutil.WriteFile("test1", byt.Bytes(), 0600) if err != nil { log.Printf("%v",err) } ```