我正在使用“查找一个”来找到特定的user_id
并返回特定文档中的数组data
。
下面是我的文档结构
package main
import (
"context" // manage multiple requests
"fmt" // Println() function
"os"
"reflect" // get an object type
// import 'mongo-driver' package libraries
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
type Fields struct {
user_id string
data struct {
year string
day string
revenue int
}
max int
}
func main() {
// Declare host and port options to pass to the Connect() method
clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
// Connect to the MongoDB and return Client instance
client, err := mongo.Connect(context.TODO(), clientOptions)
if err != nil {
fmt.Println("mongo.Connect() ERROR:", err)
os.Exit(1)
}
// Declare Context type object for managing multiple API requests
// Access a MongoDB collection through a database
col := client.Database("graph").Collection("alltime")
fmt.Println("Collection type:", reflect.TypeOf(col), "\n")
// Declare an empty array to store documents returned
var result Fields
// Get a MongoDB document using the FindOne() method
err = col.FindOne(context.TODO(), bson.D{{"user_id", "11664"}}).Decode(&result)
if err != nil {
fmt.Println("FindOne() ERROR:", err)
os.Exit(1)
} else {
// fmt.Println("FindOne() result:", result)
fmt.Println("FindOne() Name:", result.data)
// fmt.Println("FindOne() Dept:", result.Dept)
}
}
但这是我得到的输出
varun@Varuns-MacBook-Air sql-test % go run mongofind.go
Collection type: *mongo.Collection
FindOne() Name: { 0}
答案 0 :(得分:2)
驱动程序需要使用反射来设置字段,为了使反射起作用,必须导出struct字段。导出它们时,名称不再与数据库名称匹配,因此必须添加bson标记。另外,您的This is abc
字段不是struct中的数组:
Data