2018-10-08 15:27
浏览 412


I am trying to insert an array into a MongoDB instance using Go. I have the [] string slice in Go and want to convert it into a BSON array to pass it to the DB using the github.com/mongodb/mongo-go-driver driver.

var result bson.Array
    for _, data := range myData {
        value := bson.VC.String(data)

This loops over each element of my input data and tries to append it to the BSON array. However the line with the Append() fails with panic: document is nil. How should I do this conversion?

图片转代码服务由CSDN问答提供 功能建议

我正在尝试使用Go将数组插入MongoDB实例。 我在Go中有 []字符串切片,并希望将其转换为 BSON 数组,以便使用 github.com/mongodb/mongo将其传递给数据库 -go-driver 驱动程序。

为_,数据:=范围myData {
值:= bson.VC.String  (数据)

这会遍历我输入数据的每个元素,并尝试将其附加到 BSON 数组。 但是,带有 Append()的行以 panic失败:document为nil 。 我应该如何进行转换?

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • doushifang4382 2018-10-08 15:30

    Edit: The code in the question and this answer is no longer relevant because the bson.Array type was deleted from the package. At the time of this edit, the bson.A and basic slice operations should be used to construct arrays.

    Use the factory function NewArray to create the array:

    result := bson.NewArray()
    for _, data := range myData {
            value := bson.VC.String(data)
    解决 无用
    打赏 举报

相关推荐 更多相似问题