string - 如何将primitive.M转换为映射[字符串]字符串然后转换为字符串?
问题描述
我们如何将原始 M 转换为字符串?
package main
import (
"go.mongodb.org/mongo-driver/bson"
)
func main() {
a := bson.M{ // primitive.M
"test": bson.M{
"fielda": "AAA",
"fieldb": "BBB",
},
}
}
我正在使用它来记录进程中失败的 mongodb 文档。我能够使用 打印值logrus.Error
,我想将此转换复制为字符串,然后将其记录到文件中。
// cursor = "go.mongodb.org/mongo-driver/mongo" *mongo.Cursor
// logrus = "github.com/sirupsen/logrus"
//...
var temp bson.M
_ := cursor.Decode(&temp) // assume this is not returning error, it will log the map
logrus.Error("value: ", temp) // value: map[__v:0 _id:ObjectID(\"5c8ef7df7216e9935ecd7859\") field1:test]
解决方案
最简单的解决方案可能是这样使用fmt.Sprint()
:
a := bson.M{
"_id": primitive.NewObjectID(),
"test": bson.M{
"fielda": "AAA",
"fieldb": "BBB",
},
}
s := fmt.Sprint(a)
fmt.Println(s)
这将输出(在Go Playground上尝试):
map[_id:ObjectID("4af9f07018f18fbf63f00366") test:map[fielda:AAA fieldb:BBB]]
推荐阅读
- node.js - 如何将 Multer S3 流传递给另一个函数
- macos - Applescript 将 Mac 显示分辨率更改为“缩放”、“更大的文本”
- java - 如何对集合子集应用进一步的过滤器
- cakephp - CakePHP 中的自动清除消息
- nativescript - 如何在 NativeScript 中对 .udsz 文件使用 AR QuickLook?
- node.js - 如何解决 socket.io-client 连接到服务器的问题?
- python - 没有在python中正确解析嵌套的xml标签
- javascript - 如何在 JavaScript 中传递引用?
- android - Firestore:在事务中检查 NotNull 并阻止调用 OnSuccessful 回调
- python - 如何使用openpyxl将['apple','carrots','mango']等列表导出到excel的一列中?在 Python 中