如何使用Golang处理来自MongoDB文档的数据?

huangapple go评论82阅读模式
英文:

How to handle data from MongoDB document with Golang?

问题

我使用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":[]
}

如何逐行处理这些数据?例如,如何打印每个支出的类别和金额?

英文:

I get document with FindOne()

This is how document is presented in the golang:

map[
    _id:ObjectID("12") 
    chatID:12 
    expenses:[
    map[amount:12 category:food] 
    map[ ​amount:14 category:food]] 
   ​income:[]]

This is how in MongoDB Atlas:

{"_id":{"$oid":"12"},
"chatID":{"$numberInt":"12"},
"expenses":[
   ​{"category":"food","amount":{"$numberDouble":"12.0"}},
   ​{"category":"food","amount":{"$numberDouble":"14.0"}}],
"income":[]}

How to work with each line separately? For example, how to print category and amount of every expense?

答案1

得分: 2

以下是翻译好的内容:

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)
英文:
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)

答案2

得分: 0

你需要一个用于这个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)
        }
    }
}

希望能帮到你。

英文:

You need a struct for this MongoDB document:

type Fulfillment struct {
    Id       primitive.ObjectID       `bson:"_id"`
    ChatID   int64                    `bson:"chatID"`
    Expenses []map[string]interface{} `bson:"expenses"`
}

if you use MongoDB official library:

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)
		}
	}
}

I hope I've helped

huangapple
  • 本文由 发表于 2021年11月23日 18:38:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/70079370.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定