1 回答
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)
}
}
- 1 回答
- 0 关注
- 101 浏览
添加回答
举报