我得到檔案 FindOne()
這是檔案在 golang 中的呈現方式:
map[
_id:ObjectID("12")
chatID:12
expenses:[
map[amount:12 category:food]
map[ ?amount:14 category:food]]
?income:[]]
這是在 MongoDB Atlas 中的方式:
{"_id":{"$oid":"12"},
"chatID":{"$numberInt":"12"},
"expenses":[
?{"category":"food","amount":{"$numberDouble":"12.0"}},
?{"category":"food","amount":{"$numberDouble":"14.0"}}],
"income":[]}
如何分別處理每一行?例如,如何列印每筆費用的類別和金額?
uj5u.com熱心網友回復:
type List struct {
Category string `bson:"category"`
Amount float32 `bson:""amount"`
}
type Document struct {
ID primitive.ObjectID `bson:"_id, omitempty"`
ChatID int `bson:"chatID"`
Expenses []List `bson:"expense"`
Income []List `bson:"income"`
}
myDoc := Document
client.Collection.FindOne(context.TODO(), bson.D{}).Decode(&myDoc)
uj5u.com熱心網友回復:
您需要此 MongoDB 檔案的結構:
type Fulfillment struct {
Id primitive.ObjectID `bson:"_id"`
ChatID int64 `bson:"chatID"`
Expenses []map[string]interface{} `bson:"expenses"`
}
如果您使用 MongoDB 官方庫:
var fulfillment Fulfillment
err = client.Database("test_data").Collection("fulfillment").FindOne(ctx, bson.M{"chatID": 100000000012}).Decode(&fulfillment)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%d\n", fulfillment.ChatID)
fmt.Printf("%s\n", fulfillment.Id.Hex())
for _, expensive := range fulfillment.Expenses {
for k, v := range expensive {
switch v.(type) {
case string:
fmt.Printf("%s: %s \n", k, v)
case float64:
fmt.Printf("%s: %f \n", k, v)
}
}
}
我希望我有所幫助
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/364751.html
上一篇:在Go中關閉客戶端服務器通信
