如何在Golang中从MongoDB的bson.M创建多行字符串值?

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

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

问题

我正在使用Golang创建一个Telegram机器人,并且需要一些关于如何从Golang函数中检索多行字符串值的建议,该函数的逻辑与Python字符串相同。

我有一个函数,它创建一个MongoDB请求,以获取bson.M数据类型的数据。之后,我需要将这个查询到的数据作为单个字符串值发送给用户,使用以下形式:

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

我不太清楚如何将这个bson.M数据转换为单个多行字符串。

我从函数中得到的bson.M响应如下:

[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]]

我必须将它插入到名为"answer"的字符串变量中(参见上面的示例)。

提前感谢!

英文:

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!

答案1

得分: 0

循环遍历文档,并为每个文档使用sprintf生成一行。使用换行符将这些行连接起来,以获得最终结果。

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

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

huangapple
  • 本文由 发表于 2022年6月12日 23:41:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/72593655.html
匿名

发表评论

匿名网友

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

确定