'Marshal Go Struct to BSON for mongoimport

I have a slice of structs that I want to write to a BSON file for doing a mongoimport.

This a rough idea of what I'm doing (using 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())
}

This runs and generates the file, but it's not formatted correctly - instead it looks like this (using bsondump --pretty test.bson):

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

When I think it should look more like:

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

Is this possible to do in Go? I just want to generate a .bson file that you would expect a mongodump command to produce, so that I can run mongoimport and populate a colection.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source