F
F
ff3446r3e2021-11-23 13:31:48
MongoDB
ff3446r3e, 2021-11-23 13:31:48

How to work with a received document from MongoDB using Go?

I get the document using FindOne()
This is how it looks in go:

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

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

How can I, for example, display the category and amount of expenses or any other line separately?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
gill-sama, 2021-11-24
@ff3446r3e

type Expense  struct {
Category  string  `bson:"category"`
Amount   float    `bson:""amount"`
}
type MyDoc struct {
ID           primitive.ObjectID `bson:"_id, omitempty"`
ChatID       int                      `bson:"chatID"`
Expenses     []Expense              `bson:"expense"`
Income       []int(тип какой хотите) `bson:"income"`

myDoc = MyDoc{}
err = mongo.FindOne(context.TODO(),  {}).Decode(&myDoc)  
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question