1

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
  • Your document is a map. Index the map to get its elements (you might need a type assertion to access elements in a nested map). Or better, model your document with a struct, so you can simply refer to its fields. Commented Nov 23, 2021 at 10:40

2 Answers 2

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)
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.