登录
首页 >  Golang >  Go问答

如何将primitive.M转换为映射字符串,然后转换为字符串?

来源:stackoverflow

时间:2024-04-22 14:57:29 358浏览 收藏

小伙伴们对Golang编程感兴趣吗?是否正在学习相关知识点?如果是,那么本文《如何将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]]

今天关于《如何将primitive.M转换为映射字符串,然后转换为字符串?》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>