在 Mongodb 集合中如何通过 findone 方法返回数组
时间:2024-03-21
浏览:240
作者:佚名
在 MongoDB 集合中,使用 `findOne` 方法返回数组时,需要对结构体字段添加 `bson` 标签,以匹配数据库字段名称。此外,数组字段应定义为结构体切片类型,而非嵌套结构体。通过使用反射机制,驱动程序可以设置字段值,但需要导出结构体字段才能正常工作。
问题内容
我使用 find one 来查找特定的 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}解决方案
驱动程序需要使用反射来设置字段,并且为了使反射起作用,必须导出结构体字段。当您导出它们时,名称不再与数据库名称匹配,因此您必须添加 bson 标签。另外,您的 data 字段不是结构中的数组:
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 方法返回数组》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.20
11.20
11.20
11.20
热门专题
