max
max

Reputation: 686

Convert a string slice to a BSON array

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)
        result.Append(value)
}

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?

Upvotes: 1

Views: 3709

Answers (3)

rufaidulk
rufaidulk

Reputation: 374

Converting a slice of string (ids) to BSON array

var objIds bson.A
for _, val := range ids {
    objIds = append(objIds, val)
}
log.Println(objIds)

Upvotes: 0

Dai Maou
Dai Maou

Reputation: 11

As mentioned by @Cerise bson.Array has since been deleted. I do this with multiple utility functions as follows:

func BSONStringA(sa []string) (result bson.A) {
  result = bson.A{}
  for_, e := range sa {
    result = append(result, e)
  }
  return
}

func BSONIntA(ia []string) (result bson.A) {
  // ...
}

Upvotes: 1

Thundercat
Thundercat

Reputation: 120951

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)
        result.Append(value)
}

Upvotes: 3

Related Questions