登录
首页 >  Golang >  Go问答

Marshal Go Struct 为 mongoimport 的 BSON

来源:stackoverflow

时间:2024-02-12 18:12:22 374浏览 收藏

今日不肯埋头,明日何以抬头!每日一句努力自己的话哈哈~哈喽,今天我将给大家带来一篇《Marshal Go Struct 为 mongoimport 的 BSON》,主要内容是讲解等等,感兴趣的朋友可以收藏或者有更好的建议在评论提出,我都会认真看的!大家一起进步,一起学习!

问题内容

我有一个结构片段,我想将其写入 bson 文件以执行 mongoimport

这是我正在做的事情的粗略想法(使用 gopkg.in/mgo.v2/bson):

type item struct {
    id   string `bson:"_id"`
    text string `bson:"text"`
}

items := []item{
    {
        id: "abc",
        text: "def",
    },
    {
        id: "uvw",
        text: "xyz",
    },
}

file, err := bson.marshal(items)
if err != nil {
    fmt.printf("failed to marshal bson file: '%s'", err.error())
}

if err := ioutil.writefile("test.bson", file, 0644); err != nil {
    fmt.printf("failed to write bson file: '%s'", err.error())
}

这会运行并生成文件,但它的格式不正确 - 相反,它看起来像这样(使用 bsondump --pretty test.bson):

{
    "1": {
        "_id": "abc",
        "text": "def"
    },
    "2": {
        "_id": "abc",
        "text": "def"
    }
}

当我认为它应该看起来更像:

{
    "_id": "abc",
    "text": "def"
{
}
    "_id": "abc",
    "text": "def"
}

这可以在 go 中实现吗?我只想生成一个 .bson 文件,您希望 mongodump 命令生成该文件,以便我可以运行 mongoimport 并填充集合。


正确答案


您需要独立的 bson 文档,因此单独编组各个项目:

buf := &bytes.buffer{}
for _, item := range items {
    data, err := bson.marshal(item)
    if err != nil {
        fmt.printf("failed to marshal bson item: '%v'", err)
    }
    buf.write(data)
}

if err := ioutil.writefile("test.bson", buf.bytes(), 0644); err != nil {
    fmt.printf("failed to write bson file: '%v'", err)
}

运行 bsondump --pretty test.bson,输出将是:

{
        "_id": "abc",
        "text": "def"
}
{
        "_id": "uvw",
        "text": "xyz"
}
2022-02-09t10:23:44.886+0100    2 objects found

请注意,如果直接写入文件,则不需要缓冲区:

f, err := os.Create("test.bson")
if err != nil {
    log.Panicf("os.Create failed: %v", err)
}
defer f.Close()

for _, item := range items {
    data, err := bson.Marshal(item)
    if err != nil {
        log.Panicf("bson.Marshal failed: %v", err)
    }
    if _, err := f.Write(data); err != nil {
        log.Panicf("f.Write failed: %v", err)
    }
}

到这里,我们也就讲完了《Marshal Go Struct 为 mongoimport 的 BSON》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

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