gpt4 book ai didi

mongodb - 如何使用findone从Mongodb集合返回数组

转载 作者:行者123 更新时间:2023-12-01 20:27:08 25 4
gpt4 key购买 nike

我正在使用查找一个来找到特定的user_id并返回特定文档中的data数组。

下面是我的文档结构

Collection

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}

最佳答案

驱动程序需要使用反射来设置字段,并且要使反射起作用,必须导出结构字段。导出它们时,名称不再与数据库名称匹配,因此必须添加bson标记。另外,您的Data字段不是struct中的数组:

type Fields struct {
User_id string `bson:"user_id"`
Data []struct {
Year string `bson:"year"`
Day string `bson:"day"`
Revenue int `bson:"revenue"`
} `bson:"data"`
Max int `bson:"max"`
}

关于mongodb - 如何使用findone从Mongodb集合返回数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59891099/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com