khateeb
khateeb

Reputation: 5469

How to insert array of struct into MongoDB

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?

Upvotes: 6

Views: 5282

Answers (2)

mcgtrt
mcgtrt

Reputation: 787

Faster solution:

s := []any{statements}
col.InsertMany(ctx, s)

Upvotes: 0

Pocket
Pocket

Reputation: 329

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)

Upvotes: 5

Related Questions