为了账号安全,请及时绑定邮箱和手机立即绑定

元帅 Go Struct 到 BSON 用于 mongoimport

元帅 Go Struct 到 BSON 用于 mongoimport

Go
吃鸡游戏 2022-11-08 14:37:17
我有一块结构,我想将其写入 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和填充一个集合。
查看完整描述

1 回答

?
慕码人2483693

TA贡献1860条经验 获得超9个赞

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

    }

}


查看完整回答
反对 回复 2022-11-08
  • 1 回答
  • 0 关注
  • 83 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信