Home > Enterprise >  How to handle data from MongoDB document with Golang?
How to handle data from MongoDB document with Golang?

Time:11-24

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?

CodePudding user response:

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)

CodePudding user response:

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

  • Related