首页 > 解决方案 > 如何将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]

标签: stringmongodbdictionarygo

解决方案


最简单的解决方案可能是这样使用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]]

推荐阅读