script.txt 脚本文件:
db.file.insertOne({"name":"test1","age":10})
db.file.insertOne({"name":"test2","age":11})
db.file.insertOne({"name":"test3","age":12})
db.file.find({name:"test2"})
代码:
package http
import (
"context"
"fmt"
"
go.mongodb.org/mongo-driver/bson"
"
go.mongodb.org/mongo-driver/mongo"
"
go.mongodb.org/mongo-driver/mongo/options"
"os"
"strings"
"testing"
"time"
)
func TestRunMongoFile(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
clientOptions := options.Client().ApplyURI("mongodb://admin:
[email protected]:27017")
client, err := mongo.Connect(ctx, clientOptions)
if err != nil {
t.Fatal(err)
}
err = client.Ping(ctx, nil)
if err != nil {
t.Fatal(err)
}
database := client.Database("test")
fileContent, err := os.ReadFile("./script.txt")
if err != nil {
t.Fatal(err)
}
commands := strings.Split(string(fileContent), "\n")
for _, cmd := range commands {
if len(cmd) == 0 {
continue
}
var result bson.M
err = database.RunCommand(ctx, bson.D{{"eval", cmd}}).Decode(&result)
if err != nil {
t.Fatal(err)
}
fmt.Println(result)
}
}
我测试了下没啥问题,不知道是不是你要的效果,不过如果文件里执行 sql 多的话,context.WithTimeout 时间要改大一点