【问题标题】:Marshal Go Struct to BSON for mongoimport元帅 Go Struct 到 BSON 用于 mongoimport
【发布时间】:2022-02-09 17:24:21
【问题描述】:

我有一段结构,我想写入 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 并填充一个集合。

【问题讨论】:

    标签: mongodb go marshalling bson mongoimport


    【解决方案1】:

    您想要独立的 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)
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-15
      • 2011-05-24
      • 2019-04-06
      • 1970-01-01
      • 1970-01-01
      • 2021-03-05
      相关资源
      最近更新 更多