Tengo una porción de estructuras que quiero escribir en un archivo BSON para hacer una mongoimport .
Esta es una idea aproximada de lo que estoy haciendo (usando 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()) } Esto ejecuta y genera el archivo, pero no tiene el formato correcto; en cambio, se ve así (usando bsondump --pretty test.bson ):
{ "1": { "_id": "abc", "text": "def" }, "2": { "_id": "abc", "text": "def" } }Cuando creo que debería parecerse más a:
{ "_id": "abc", "text": "def" { } "_id": "abc", "text": "def" } ¿Es posible hacerlo en Go? Solo quiero generar un archivo .bson que esperaría que produjera un comando mongodump , para que pueda ejecutar mongoimport y completar una colección.
Desea documentos BSON independientes, así que organice los elementos individualmente:
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) } Ejecutando bsondump --pretty test.bson , el resultado será:
{ "_id": "abc", "text": "def" } { "_id": "uvw", "text": "xyz" } 2022-02-09T10:23:44.886+0100 2 objects foundTenga en cuenta que el búfer no es necesario si escribe directamente en el archivo:
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) } }