How to make a multiline string value from MongoDB's bson.M in Golang?

Issue

I’m creating a telegram bot using Golang, and I need some advice on how to retrieve a multiline string value from function in Golang, that has same logic like this Python string

answer = """1 John 95
2 Sam 89
3 Mike 72"""

I have a function that creates a MongoDB request that gets me a data in bson.M datatype. And after that I need to send this queried data to a user as a single string value using this form:

msg := tgbotapi.NewMessage(
    update.Message.Chat_ID,
    answer,
)
bot.Send(msg)

I don’t really know how to transform this bson.M data into a single multiline string.

bson.M response that I get from the function:

[map[_id:ObjectID("62a4acf2a494a2814238c6e1") bandMember:John name:School12 points:95] 
map[_id:ObjectID("62a4acf2a494a2814238c6e2") bandMember:Sam name:School15 points:89] 
map[_id:ObjectID("62a4acf2a494a2814238c6e3") bandMember:Mike name:School7 points:72]]

And I have to insert it in a string variable of "answer" (see above example)

Thanks in advance!

Solution

Loop through the documents and sprintf a line for each document. Join the lines with newline to get the final result.

var lines []string
for i, m := range data {
    lines = append(lines, fmt.Sprintf("%d %s %d", i+1, m["bandMember"], m["points"]))
}
result := strings.Join(lines, "\n")

Answered By – Bellingham Boss

Answer Checked By – Pedro (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.