我正在尝试使用该库将存储在结构数组中的数据插入到 MongoDB 中go.mongodb.org/mongo-driver。我的结构是
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"`
}
Run Code Online (Sandbox Code Playgroud)
我的插入代码是
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
}
Run Code Online (Sandbox Code Playgroud)
cannot use stmts (variable of type []Statement) as []interface{} value in argument to testCollection.InsertMany编译器在命令中给出错误InsertMany。
我已经尝试在插入之前对结构进行编组使用bson.Marshal,但即使这样也不起作用。如何将这些数据插入数据库?
insertMany 接受[]interface{}
我会这样做
newValue := make([]interface{}, len(statements))
for i := range statements {
newValue[i] = statements[i]
}
col.InsertMany(ctx, newValue)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4081 次 |
| 最近记录: |