golang 操作 mongo
最后更新于:2022-04-02 04:00:17
[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"))
if err != nil {
panic(err )
}
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")
```
## 创建索引
### 创建单个索引
```
coll := mon.Database(databases).Collection(collection)
index := mongo.IndexModel{
Keys: bson.M{
"msg_id": "",
// "recv_id": "",/创建单索引多字段
},
Options: options.Index().SetSparse(true),//需要在集合中某字段创建索引,但集合中大量的文档不包含此键值时,建议创建稀疏索引。
}
many, err := coll.Indexes().CreateOne(context.Background(), index)
if err != nil {
log.Errorf("many []string:%v err:%v\n",many,err)
}
```
### 创建多个索引
```
coll := db.Collection("test")
index := []mongo.IndexModel{
{
Keys: bsonx.Doc{{Key: "name", Value: bsonx.String("text")}},
},
{
Keys: bsonx.Doc{{Key: "createdAt", Value: bsonx.Int32(-1)}},
},
}
opts := options.CreateIndexes().SetMaxTime(10 * time.Second)
_, errIndex = coll.Indexes().CreateMany(context, index, opts)
if err != nil {
panic(errIndex)
}
```
## 插入
### 插入单挑条
```
//连接库名,连接集合名
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)
}
```
';