Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

205
Views
Marshal Go Struct a BSON para mongoimport

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.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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 found

Tenga 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) } }
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!