我想从singleResult
的{{1}}的{{1}}获取一个FindOne
,然后使用Collection
或moviesCollection
来放置这些值成一个结构。结构Decode
中的值与每个Unmarshal
我正在使用官方的mongodb驱动程序JSONData
以下是我尝试过的示例:
Document
但是不会产生任何错误,github.com/mongodb/mongo-go-driver
会产生一个空字符串。
我也尝试使用mongoContext, cancelContext := context.WithTimeout(context.Background(), 10*time.Second)
defer cancelContext()
mongoClient, _ := mongo.Connect(mongoContext, options.Client().ApplyURI("mongodb://localhost:27017"))
moviesCollection := mongoClient.Database("Entertainment").Collection("Movies")
moviesCollection.InsertOne(mongoContext, bson.M{"_id": "Deadpool", "Path": "path/to/file"})
singleResult := moviesCollection.FindOne(mongoContext, bson.M{"_id": "Deadpool"})
if singleResult.Err() != nil {
log.Println("Find error: ", singleResult.Err())
}
JSONData := struct {
Path string `json:"Path"`
}{}
decodeError := singleResult.Decode(&JSONData)
if decodeError != nil {
log.Println("Decode error: ", decodeError)
}
fmt.Println("Path: ", JSONData.Path)
代替JSON.Path
我可以确认bson.D{{"_id", "Deadpool"}}
不是空字符串,因为我已经使用bson.M{"_id": "Deadpool"}
本地检查了数据库。 该条目包含以下内容:
JSON.Path
答案 0 :(得分:8)
在内部,MongoDB使用 bson 。如下更改结构即可。
来自
JSONData := struct {
Path string `json:"Path"`
}{}
到
JSONData := struct {
Path string `bson:"Path"`
}{}
答案 1 :(得分:2)
嘿,就像simagix提到的那样,您应该可以将标签从JSON更改为bson:
`bson:"Path"`
另一个选择,如果您需要获得更通用的结果,则可以像这样将其传递给D对象:
JSONData := &bson.D{}
decodeError := singleResult.Decode(JSONData)
然后您可以使用JSON.Data.Map函数通过地图获取所有信息。
答案 2 :(得分:0)
如果您使用的是mongo-go-driver >= v.0.1.0
,那么看看go-doc看起来很简单:
filter := bson.D{{"hello", "world"}}
err := collection.FindOne(context.Background(), filter).Decode(&result)
if err != nil { return err }
// do something with result...
因此,您需要的是:
package main
import (
"context"
"github.com/mongodb/mongo-go-driver/bson"
"github.com/mongodb/mongo-go-driver/mongo
)
func main() {
ctx := context.Background()
client, err := mongo.NewClient("mongodb://localhost:27017")
if err != nil {
...
}
if err := client.Connect(ctx); err != nil {
...
}
defer client.Disconnect(ctx)
collection := client.Database("myDb").Collection("movies")
filter := bson.D{{"_id", "sometitle"}}
var result JSONData
err := collection.FindOne(ctx, filter).Decode(&result)
if err != nil {
...
}
// Do Something cool here
}
我看到您正在使用Title
来过滤文档。注意。