How to insert array of struct into MongoDB

Viewed 1585

I am trying to insert data that is stored in an array of struct into a MongoDB using the go.mongodb.org/mongo-driver library. My struct is

type Statement struct {
    ProductID        string `bson:"product_id" json:"product_id"`
    ModelNum         string `bson:"model_num" json:"model_num"`
    Title            string `bson:"title" json:"title"`
}

and my insertion code is

func insert(stmts []Statement) {
    client, err := mongo.NewClient(options.Client().ApplyURI("mongodb://127.0.0.1:27017"))
    if err != nil {
        log.Fatal(err)
    }
    ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
    err = client.Connect(ctx)
    if err != nil {
        log.Fatal(err)
    }
    defer client.Disconnect(ctx)

    quickstartDatabase := client.Database("quickstart")
    testCollection := quickstartDatabase.Collection("test")
    testCollection.InsertMany(ctx, stmts) // This is giving error
}

The compiler gives the error cannot use stmts (variable of type []Statement) as []interface{} value in argument to testCollection.InsertMany at the InsertMany command.

I have tried marshalling the struct before inserting using bson.Marshal but even that doesn't work. How do I insert this data into the DB?

1 Answers

insertMany accept []interface{}

i would make like this

newValue := make([]interface{}, len(statements))

for i := range statements {
  newValue[i] = statements[i]
}

col.InsertMany(ctx, newValue)
Related