1 回答

TA貢獻(xiàn)1860條經(jīng)驗(yàn) 獲得超9個(gè)贊
您需要獨(dú)立的 BSON 文檔,因此請(qǐng)單獨(dú)編組這些項(xiàng)目:
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)
}
運(yùn)行bsondump --pretty test.bson,輸出將是:
{
"_id": "abc",
"text": "def"
}
{
"_id": "uvw",
"text": "xyz"
}
2022-02-09T10:23:44.886+0100 2 objects found
請(qǐng)注意,如果您直接寫(xiě)入文件,則不需要緩沖區(qū):
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)
}
}
- 1 回答
- 0 關(guān)注
- 131 瀏覽
添加回答
舉報(bào)