golang 查询mongodb集合 返回匹配的OwnerID下全部的name和QuotaSize的结构体数组,如果QuotaSize为空则默认为0
时间: 2023-01-11 08:55:36 浏览: 73
好的,下面是一个示例代码。
```
package main
import (
"context"
"fmt"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
type MyStruct struct {
Name string
QuotaSize int
}
func main() {
// 创建 MongoDB 连接
client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI("mongodb://localhost:27017"))
if err != nil {
fmt.Println(err)
return
}
defer client.Disconnect(context.TODO())
// 选择数据库和集合
collection := client.Database("mydb").Collection("mycoll")
// 构建过滤器
filter := bson.M{"OwnerID": "123"}
// 查询符合过滤器的文档
cursor, err := collection.Find(context.TODO(), filter)
if err != nil {
fmt.Println(err)
return
}
defer cursor.Close(context.TODO())
// 遍历结果集
var results []MyStruct
for cursor.Next(context.TODO()) {
// 定义一个指针类型的变量
var elem MyStruct
err := cursor.Decode(&elem)
if err != nil {
fmt.Println(err)
return
}
// 如果 QuotaSize 为空,则默认为 0
if elem.QuotaSize == 0 {
elem.QuotaSize = 0
}
results = append(results, elem)
}
if err := cursor.Err(); err != nil {
fmt.Println(err)
return
}
// 打印结果
fmt.Println(results)
}
```
这段代码中,我们使用了 MongoDB Go 驱动的 Find() 方法来查询符合过滤器的文档。然后使用一个循环来遍历结果集,并使用 Decode() 方法将每个文档解码到一